How to compare Date in Shell script ?
There is no in built function to compare dates in shell script . So we need to convert every date to second value from 1970 using ( date +%s ) option
After that we can compare it
[sterin@stjacob-lap ~]$ date
Thu Sep 17 15:10:28 IST 2015
[sterin@stjacob-lap ~]$ date +%s
1442482830
Example :
Date format is : 16/Sep/2015:16:20:32 dd/Mmm/YYY:HH:MM:SS
Date 1 : 16/Sep/2015:16:20:32
Date 2 : Current System date
Script :
----------------------------------------------------------------------------------------------------
# #1 is input date to compare with system time
now=`date +%s`
dt1=`echo $1 | sed 's:/:-:g; s/:/ /'`
t1=`date --date="$dt1" +%s`
let "tDiff=$now-$t1"
let "hDiff=$tDiff/3600"
if [ $hDiff -lt 1 ]
then
echo " System Date is Eariler "
else
echo " System Date is Later "
fi
---------------------------------------------------------------------------------------------------------
Output
[oracle@stjacob-pc1 tmp]$ ./datecompare.sh 16/Sep/2015:16:21:36
System Date is Later
[oracle@stjacob-pc1 tmp]$ ./datecompare.sh 20/Sep/2015:16:21:36
System Date is Eariler
There is no in built function to compare dates in shell script . So we need to convert every date to second value from 1970 using ( date +%s ) option
After that we can compare it
[sterin@stjacob-lap ~]$ date
Thu Sep 17 15:10:28 IST 2015
[sterin@stjacob-lap ~]$ date +%s
1442482830
Example :
Date format is : 16/Sep/2015:16:20:32 dd/Mmm/YYY:HH:MM:SS
Date 1 : 16/Sep/2015:16:20:32
Date 2 : Current System date
Script :
----------------------------------------------------------------------------------------------------
# #1 is input date to compare with system time
now=`date +%s`
dt1=`echo $1 | sed 's:/:-:g; s/:/ /'`
t1=`date --date="$dt1" +%s`
let "tDiff=$now-$t1"
let "hDiff=$tDiff/3600"
if [ $hDiff -lt 1 ]
then
echo " System Date is Eariler "
else
echo " System Date is Later "
fi
---------------------------------------------------------------------------------------------------------
Output
[oracle@stjacob-pc1 tmp]$ ./datecompare.sh 16/Sep/2015:16:21:36
System Date is Later
[oracle@stjacob-pc1 tmp]$ ./datecompare.sh 20/Sep/2015:16:21:36
System Date is Eariler
No comments:
Post a Comment