Difference between revisions of "Date Shift Script"
Line 39: | Line 39: | ||
</nowiki></pre> | </nowiki></pre> | ||
Just save it somewhere in the Cygwin path (e.g. <tt>/usr/local/bin</tt> is a good place) as dateshift and make it executable (<tt>[[UNIX filesystem permissoins tutorial|chmod u+x datescript]]</tt>) | Just save it somewhere in the Cygwin path (e.g. <tt>/usr/local/bin</tt> is a good place) as dateshift and make it executable (<tt>[[UNIX filesystem permissoins tutorial|chmod u+x datescript]]</tt>) | ||
[[Category:Unix]][[Category:Computing]] | |||
==Example Usage== | ==Example Usage== |
Revision as of 01:56, 2 May 2006
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.
dateshift
I use the following simple 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 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) EOF 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"
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 20060306
- 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