Date Shift Script

From assela Pathirana
Revision as of 01:11, 2 May 2006 by Root (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to 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 have written the following UNIX script to add or substract number of days from a given date and print the result.

#!/bin/bash
fmt="+%Y%m%d"
if [ $# -lt 1 ]; then
  echo "Usage: $0 ndates date  [ADD/SUB]"
  echo "default format is $fmt" 
  echo "format should be YYYYMMDD or any other acceptable format for date command"
  echo "full precision down to seconds (if specified will be computed) but only up to date will be printed by default"
  echo "default is to add"
  echo "if third argument is SUB, then substracted"
  echo "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"
  
  exit 1
fi
dates=$1
if [ $# -ge 2 ]; then
  thisdate=`date --date "$2" +'%s'`
else
  date=''
  thisdate=`date +'%s'`
fi
if [ !  "$3" == 'SUB' ];then 
  newdate=`echo $thisdate $dates|awk '{printf "%20i", $1+$2*24*3600}'`
else
  newdate=`echo $thisdate $dates|awk '{printf "%20i", $1-$2*24*3600}'`
fi
if [ $# -ge 4 ]; then
  fmt=$4
fi

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