hello
i have obtained the current date ..
current_date=date "+%m/%d%y"
and i have another date ,stored in my log file which i have already retrieved. i want to store the subtraction in a varible called diff.
diff=log_date - currentdate
ex: log_date=01/28/11
current_date= 02/25/11
then diff=28
Hi, Try the below bash script ,
Date_Difference_Days.sh
#!/bin/sh
cur_date=`date "+%m/%d/%y"`
log_date='01/28/11'
echo $log_date $cur_date | awk '
BEGIN {
d[1] = 31
d[2] = 28
d[3] = 31
d[4] = 30
d[5] = 31
d[6] = 30
d[7] = 31
d[8] = 31
d[9] = 30
d[10] = 31
d[11] = 30
d[12] = 31
}
{
yr=substr($1,7,2);mon=substr($1,1,2);day=substr($1,4,2)
yr1=substr($2,7,2);mon1=substr($2,1,2);day1=substr($2,4,2)
if((yr % 4 == 0 && yr % 100 != 0) || yr % 400 == 0) { d["02"] = 29;}
if ((yr1 - yr)==0 && (mon1-mon)==0) {print day1-day;exit}
if ((yr1 - yr)==0 && (mon1-mon)!=0)
{
for (i=mon+1;i<int(mon1);i++){dayadd+=d}
print day1+(d[int(mon)]-day)+dayadd
exit
}
if ((yr1 - yr)!=0)
{
mon_new=mon
for(j=yr;j<yr1;j++)
{
for (i=mon_new+1;i<=12;i++){dayadd+=d}
mon_new=0
}
for (i=1;i<int(mon1);i++){dayadd+=d}
print "Days Diff :- " day1+(d[int(mon)]-day)+dayadd
exit
}
}'
panyam
3
one more version , but this does have some limitations , like year<=2099 etc.
#!/bin/sh
get_JD () {
scale=0
echo " $1-32075+1461*($3+4800+($2-14)/12)/4+367*($2-2-($2-14)/12*12)/12-3*(($3+4900+($2-14)/12)/100)/4 " | bc
}
first=`get_JD 1 1 2011`
second=`get_JD 1 3 2011`
diff=`expr $second - $first`
echo $diff
I googled it on my intereset. The logic applied here seems to be an algo used in US Navy. I don't have much idea how this is working!!!
kshji
4
Using gnu date
from="20100401"
to="20100503"
start=$(date --date="$from" +"%s")
end=$(date --date="$to" +"%s")
days=$(( (end - start) / 86400 ))
echo $days
from="04/01/11"
to="05/03/11"
start=$(date --date="$from" +"%s")
end=$(date --date="$to" +"%s")
days=$(( (end - start) / 86400 ))
echo $days
Using ksh93 builtin printf
((day=24*60*60)) # 86400 s
fromdate="04/01/11"
todate="05/03/11"
# datestr => epoc
epoc1=$(printf "%(%#)T" "$fromdate")
epoc2=$(printf "%(%#)T" "$todate")
# length of day (seconds) = 86400
echo $(( (epoc2-epoc1) /day))
fromdate="2011-04-01"
todate="2011-05-03"
# datestr => epoc
epoc1=$(printf "%(%#)T" "$fromdate")
epoc2=$(printf "%(%#)T" "$todate")
echo $(( (epoc2-epoc1) /day))
Or using calculating like panyam.
More about calculating
Is there a formula for calculating the Julian day number?
You can do panyam solution without any external commands, using builtin in every posix compatible shells (bash, ksh93, dash, ...)
get_JD()
{
d="$1"
m="$2"
y="$3"
echo $(( d-32075+1461*(y+4800+(m-14)/12)/4+367*(m-2-(m-14)/12*12)/12-3*((y+4900+(y-14)/12)/100)/4 ))
}
first=$( get_JD 1 4 2011 ) # day month year
second=$( get_JD 4 5 2011 )
diff=$((second - first))
echo $diff