I am using Sun OS, I want my script to read date from a file(in format %Y%m%d) and add 1 day to that date

135 Views Asked by At

I am working in Sun OS environment, I want to add a functionality to my existing unix ksh script where it allows to read a date(in %Y%m%d format) from a file and add 1 day and rewrite the same into that file. [please note: not adding day to current date instead i want to add 1 day to i/p date present in a file]. Eg:DateFile.dat 20200620 I want my script to change it to 20200621 at the end of run. My code as below:

#!/bin/ksh
ip_dte</home/{file_Path}
echo $ip_dte
dte_add=`TZ=AEST-24 "$ip_dte"`
echo $dte_add
4

There are 4 best solutions below

1
Andre Gelinas On

Something like that ? :

#!/bin/ksh

# Starting date, YYYYMMDD (yes I should verify the format :) )
FIRST_DATE=$1
[[ -z $FIRST_DATE ]] && FIRST_DATE=$(date +"%Y%m%d")

# 1 day in seconds
PERIOD=86400

# Transform the starting date in second and add 1 day
SECOND_DATE=$(( $(date -d "$FIRST_DATE" +"%s")+$PERIOD ))

# Transform the second date from second to human date format
print "Second date is $(date -d @"$SECOND_DATE" +"%Y%m%d")"
3
markp-fuso On

We can let date do the calculations and formatting for us:

$ date1='20200415'

$ date -d "${date1}+1 day"                     # add 1 day, use default output format
Thu Apr 16 00:00:00 UTC 2020

$date -d "${date1}+1 day" '+%Y%m%d'            # add 1 day, change to YYYYMMDD format
20200416

$ date2=$(date -d "${date1}+1 day" '+%Y%m%d')  # save new date in variable in YYYYMMDD format
$ echo "${date2}"
20200416

Here's a ksh fiddle of the above.

2
Mark Plotnick On

The other answers will work if you have ‎CSWcoreutils or SUNWgnu-coreutils installed. You may have to run gdate or /usr/gnu/bin/date.

But if you have a recent version of Solaris, ksh will be ksh93, and you can use the %T format in printf:

$ cat ddd
20200620
$ ip_dte=`cat ddd`
$ printf "%(%Y%m%d)T\n" "$ip_dte tomorrow"
20200621
2
LeadingEdger On

If you have perl with the Time::Local module on the old Solaris server, try this:

#!/bin/ksh
ip_dte=20200531 # or read date from file into ip_dte
echo $ip_dte
timestamp=`perl -MTime::Local=timelocal -e '($y,$m,$d) = $ARGV[0] =~ /(\d\d\d\d)(\d\d)(\d\d)/; $m=$m-1; print timelocal(1,1,1,$d,$m,$y);' $ip_dte`
dte_add=`perl -MPOSIX=strftime -e 'print strftime("%Y%m%d", localtime($ARGV[0] +86400));' $timestamp`
echo $dte_add