Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

subtracting two dates

Status
Not open for further replies.

daddymack

MIS
Nov 13, 2001
15
IE
Does anyone know of a quick way of subtracting two dates from one another in awk
i.e date format is YYYYMMDD
in order to find the number of days between them ?
 
Looks like noone knows an easy way. Maybe if I submit a hard way, it will spur someone into action. This has been only lightly tested and does no error checking.
Code:
BEGIN {
  m[1]=31;m[2]=28;m[3]=31;m[4]=30;
  m[5]=31;m[6]=30;m[7]=31;m[8]=31;
  m[9]=30;m[10]=31;m[11]=30;m[12]=31;
}
{
  y1 = substr($1,1,4)
  m1 = substr($1,5,2)+0
  d1 = substr($1,7,2)
  y2 = substr($2,1,4)
  m2 = substr($2,5,2)+0
  d2 = substr($2,7,2)
  if (y1==y2 && m1==m2)
    dd = d2-d1
  else {
    m[2] = 28
    if (y1%4==0 && (y1%100!=0 || y1%400==0)) m[2]=29
    dd = m[m1]-d1
    em = m2
    if (y2>y1) em=13
    for (i=m1+1;i<em;i++) dd+=m[i]
    for (i=y1+1;i<y2;i++) {
      dd+=365;
      if (i%4==0 && (i%100!=0 || i%400==0)) dd++
    }
    if (y2>y1) {
      m[2] = 28
      if (y2%4==0 && (y2%100!=0 || y2%400==0)) m[2]=29
      for (i=1;i<m2;i++) dd+=m[i]
    }
    dd+=d2;
  }
  print y1 &quot; &quot; m1 &quot; &quot; d1 &quot; &quot; y2 &quot; &quot; m2 &quot; &quot; d2 &quot; &quot; dd
}
Looking forward to seeing a better solution. CaKiwi
 
Thanks CaKiwi for the post, but in order to keep processing time to a minimum, I have decided to go with the idea of using a lookup table of epoc values with the key

MON-YYYY%NNNNNN

where NNNNNN is the number of days from the end of the previous month since 1/1/1970 e.g

JAN-1970%0
FEB-1970%31 #31 days from 31/1/70 to 1/1/70
MAR-1970%59 #59 days from 28/2/70 to 1/1/70
and so forth until 2050.

I have used month/year combination so that the size of lookup array is kept as small as possible.
I load up into an array called days_since whose index is the value MON-YYYY

Now, in order to get the epoch date for a date, all I do is do a quicklookup on an array and add the date portion of the date I am looking for, i.e if I want epoch date of
21-JUL-1974, I compute

days_since[JUL-1974] + 21

If I am subtracting dates, I just get the epoch date of the second date and subtract the epoch values. This gives me the number of days in the difference

You can also compare dates using this method.

Hope this can be of use to anyone else doing date arithmetic
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top