Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I get any date relative to today (in ksh)

How do I get any date relative to today (in ksh)

by  PHV  Posted    (Edited  )
Here a simple ksh function to get any date in the past or in the future from today.
It takes two arguments, the first is mandatory and is the number of days from today (negative for backward) and the second one is optional and is the format you want the date command uses.
Code:
GetDate(){ # GetDate nDays [format]
  typeset -i nDays=$1; format=$2
  eval $(echo $TZ | sed '
s!\([^-0-9]*\)\([-0-9]*\)\(.*\)!typeset -i localOffset=\2;zon1=\1;zon2=\3!')
  TZ=$zon1$((localOffset-24*nDays))$zon2 date $format
}
#-- Examples:
Code:
echo "Yesterday: $(GetDate -1)"
echo "Tomorrow: $(GetDate 1)"
echo "Next week: $(GetDate 7 '+%Y-%m-%d')"
#-- Note:
On some *nix flavor the authorized displacement is limited to +/-168 hours and thus the above "Next week" test fails.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top