Unix shell script to calculate date in the future and in the past

 

For Linux use the following commands:

$ date -d 'now + 12 days' (12 days in the future)
$ date -R --date="-14 days" (14 days in the past)

What if you have Solaris "date", then you need the below.

Let's say we need to calculate yesterday's date. This script is for Solaris only, and it is using (/abusing) TZ beyond its stated purpose. You can advance unlimited time into the future, but only 6 days into the past.

Test:

date.sh 1 past short

Content:

cat date.sh
#!/bin/ksh
if [ $# -ne 3 ]; then
 print "Usage: `basename $0` < NUMBER_OF_DAYS > < past|fut > < short|long|slong >"
 exit 1
fi
DAYS=$1
WHEN=$2
FORM=$3
ZONE=`date +%Z`
if [ "${ZONE}" = "EDT" ]; then
 HR_DIFF=4
elif [ "${ZONE}" = "EST" ]; then
 HR_DIFF=5
else
 print "${ZONE} is invalid"
 exit 1
fi
 
if [ "${WHEN}" = "past" ]; then
 SYM="+"
 HOURS=`expr ${DAYS} \* 24 + ${HR_DIFF}`
elif [ "${WHEN}" = "fut" ]; then
 SYM="-"
 HOURS=`expr ${DAYS} \* 24 - ${HR_DIFF}`
else
 print "${WHEN} is invalid"
 exit 1
fi

if [ "${FORM}" = "short" ]; then
 echo "`TZ=${ZONE}${SYM}${HOURS} date +%Y%m%d`"
elif [ "${FORM}" = "long" ]; then
 echo "`TZ=${ZONE}${SYM}${HOURS} date '+%b %d, %Y'`"
elif [ "${FORM}" = "slong" ]; then
 echo "`TZ=${ZONE}${SYM}${HOURS} date '+%b %d, %Y %H:%M'`"
else
 print "${FORM} is invalid"
exit 1
fi

exit 0

Moving your apps to Amazon or Miscrosoft Clouds?

We can help you analyze your existing infrastructure, identify the cost savings we can achieve by migrating to a cloud provider. We can then execute end-to-end migration plan of your infrastructure and bringing down your TCO.

Cloud Computing

Ready for IPv6 Migration?

The Internet is running out of the equivalent of phone numbers - familiar problem, non-trivial solution.

The world has to move to IPv6, with its 128-bit addresses. But that's easier said than done.

IPv6 Migration

Are you fluent in "Linux"?

Learn Linux from a leading expert and quickly master you Linux skills.

Learn how to simplify your workflow and increase your productivity using tips and techniques of the pros.

Ideal training for Corporate IT Beginners and Advanced IT Admins alike.

Corporate Linux Training

Who's Online

We have 6 guests and no members online