Date and Time comparison using shell script

Hi,
I'm having two fields in the file
F1|F2
20111220|102000

F1 ->YYYYMMDD
F2 ->HHMMSS

Now, I need to compare this with current date & time and need to return the difference value in hours. Already, I checked with datecalc from the forum. So, need hints from Shell Gurus.

Thanks

Using awk

cat infile
20111220|102000
awk -F"|" '{ x=$1;y=$2;
  diff=systime()-mktime(substr(x,0,4)OFS substr(x,5,2)OFS substr(x,7,2)OFS substr(y,0,2)OFS substr(y,3,2)" 00")
  print diff/3600 " Hours"
}' infile

If solaris, use nawk

Using date command

#!/bin/bash

read data < infile

DATE=${data%%|*}
TIME=$( echo ${data##*|} | sed 's/../&:/g;s/:$//' )

sec=$( date -d "$DATE $TIME" +%s )
curr=$( date +%s )

((diff=(curr-sec)/3600))
echo "$diff Hours"

--ahamed

1 Like

Thanks for prompt reply.

Anyhow, I'm unable to use systime or mktime; because my OS version is AIX 6.x.

Also, date -d is not a valid option in AIX.
So, please let me know if you have any other alternatives or how can I pass systime/mktime in AIX.

Thanks

See if you have gawk installed.

--ahamed

"gawk" is not installed. We only have awk and nawk in our servers.

Try with nawk in that case

--ahamed

awk and nawk are getting the same error.

awk: Function systime is not defined.

The input line number is 1. The file is abc.log.
The source line number is 2.

Thanks

Instead of systime() use strftime("%s") and give it a try!

awk -F"|" '{ x=$1;y=$2;
  diff=strftime("%s")-mktime(substr(x,0,4)OFS substr(x,5,2)OFS substr(x,7,2)OFS substr(y,0,2)OFS substr(y,3,2)" 00")
  print diff/3600 " Hours"
}' infile

--ahamed

strftime, systime and mktime are getting the same errors in AIX. We don't have C/C++ compilers on these servers. I don't know how to call these system calls.

Perl.

perl -ne 'use Time::Local;
$diff=time-timelocal(substr($_,13,2),substr($_,11,2),substr($_,9,2),substr($_,6,2),substr($_,4,2)-1,substr($_,0,4));
print $diff ."\n";' input.txt

If it's feasible for you to use an external helper tool, check out my dateutils (http://hroptatyr.github.com/dateutils).

ddiff -i '%Y%m%d|%H%M%S' "20111220|102000" now -f '%H'
=> 3003

The -i is the input format, -f the output format (difference in hours), and "20111220|102000" is your F1|F2, now is the value to compute the difference from.