Date Shift Script

From assela Pathirana
Jump to: navigation, search

Let's face it: Solar system is a mess as far as time units are concerned! There are some 365.2425 days and is reducing with time!! We have largely simplified the system by adopting various convensions in the standard calendar, still there are occational jumps of dates here are there. This causes numerous problems in writing programs that operate on dates. Perhaps the best bet is to use a standard date function provided by an operating system as the basis, for these systems have been widely researched and tested.


I use the following simple UNIX script to add or substract number of days from a given date and print the result.

if [ $# -lt 1 ]; then
  cat << EOF 
  Usage: $0 ndates date  [ADD/SUB] [fmt]
  default format is $fmt  
  format should be YYYYMMDD or any other acceptable format for date command 
  full precision down to seconds (if specified will be computed) but only 
  up to date will be printed by default 
  default is to add 
  if third argument is SUB, then substracted 
  if a forth argument is present, it is treated as the format specifier 
  for output. e.g.  '+%Y%m%d%H%M%S' to get full precision 
  (Assela Pathirana, 2006)  
  exit 1
if [ $# -ge 2 ]; then
  thisdate=`date --date "$2" +'%s'`
  thisdate=`date +'%s'`
if [ !  "$3" == 'SUB' ];then
  newdate=`echo $thisdate $dates|awk '{printf "%20i", $1-$2*24*3600}'`
  newdate=`echo $thisdate $dates|awk '{printf "%20i", $1+$2*24*3600}'`
if [ $# -ge 4 ]; then

date  --date=" 1970-01-01 00:00:00 UTC $newdate  seconds"  "$fmt"

Just save it somewhere in the Cygwin path (e.g. /usr/local/bin is a good place) as dateshift and make it executable (chmod u+x datescript)

Example Usage

  • Add five days to 2006-03-01:
$ dateshift 5 20060301 
  • Add 12 hours to 20060304 06:00:
$ dateshift .5 "20060304 06:00"  "+%Y%m%d %H:%M"
20060304 18:00
  • Subtract five days and six hours from 20060308:
$ dateshift -5.25 20060308 "+%Y%m%d %H:%M"
20060302 18:00