Compare dates

Hi,

I want to convert two datetime fields to find out if the difference is one hour, in linux I've done this by converting both the datetime values to unix epoch time and subtracting them to find out if the difference is more than 3600s, however this does not work in hp-ux.

I've these variable inside an awk script, and I'm getting the date values inside the script by:

"date +%Y%m%d%H%M%S" | getline current_time

Any ideas?

For a start:

ra:/home/vbe $  "date +%Y%m%d%H%M%S"
/usr/bin/ksh: date +%Y%m%d%H%M%S:  not found
ra:/home/vbe $ date "+%Y%m%d%H%M%S"  
20100817105902
ra:/home/vbe $ 

Hi.

That's awk code, so the quotes execute the date command, similar to using system().

As %s is not supported in HP-UX date, perhaps you can use perl?

$ perl -e "print time();"
1282036192

I solved it in a rather tedious way,

You'll have the old time time1 and new time2 which you'll get through

"date +%Y%m%d%H%M%S" | getline timex

First idea was to convert the whole time into seconds similar to epoch time, and subtract the two times, but the seconds conversion would give a very large number making the awk variables overflow and show incorrect values.

Then the other way I came up with was to extract the year,month,day,hour,min and seconds into separate variables using substr(),

  • year2 - year1 can be 0 or 1 i.e
    [list]
  • same year will give diff of 0
  • if time was dec31 before midnight and next time was jan01 after midnight will give diff of 1
    [/list]
  • month2 - month1 can be 0, 1 or -11 i.e
    [list]
  • same month will give 0
  • previous month before midnight diff new month after midnight will give 1
  • if it was dec31st and jan1st the diff will be -11
    [/list]
  • day2 - day1 can be 0, 1, 30, 29, 27
    [list]
  • same day = 0
  • previous day midnight - new day midnight = 1
  • if the days fell on two different months it'll be 31st -1 or 30th - 1 or 28th -1 for feb
    [/list]

Finally if the year, month and day differences fall within the above ranges, then we're left with hours, min and sec, which we can easily convert to seconds and check if it is greater than 3600 sec and that is how you check two datetime differences :slight_smile:
Performance of the script is very good :wink:

Let me know if there is a better way of doing this....