Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

UNIX Scripting FAQ

How do I get any date relative to today (in ksh) by PHV
Posted: 2 Feb 04 (Edited 2 Nov 12)

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.


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:


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.

Back to UNIX Scripting FAQ Index
Back to UNIX Scripting Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close