Date arithmetic in Unix shell scripts

前端 未结 14 1508
生来不讨喜
生来不讨喜 2020-11-27 22:29

I need to do date arithmetic in Unix shell scripts that I use to control the execution of third party programs.

I\'m using a function to increment a day and another

14条回答
  •  無奈伤痛
    2020-11-27 22:43

    If you want to continue with awk, then the mktime and strftime functions are useful:

    
    BEGIN { dateinit }
          { newdate=daysadd(OldDate,DaysToAdd)}
    
     # daynum: convert DD-MON-YYYY to day count
     #-----------------------------------------
    function daynum(date,  d,m,y,i,n)
    {
         y=substr(date,8,4)
         m=gmonths[toupper(substr(date,4,3))]
         d=substr(date,1,2)
         return mktime(y" "m" "d" 12 00 00")
    }
    
     #numday: convert day count to DD-MON-YYYY
     #-------------------------------------------
    function numday(n,  y,m,d)
    {
        m=toupper(substr(strftime("%B",n),1,3))
        return strftime("%d-"m"-%Y",n)
    }
    
     # daysadd: add (or subtract) days from date (DD-MON-YYYY), return new date (DD-MON-YYYY)
     #------------------------------------------
    function daysadd(date, days)
    {
        return numday(daynum(date)+(days*86400))
    }
    
     #init variables for date calcs
     #-----------------------------------------
    function dateinit(   x,y,z)
    {
         # Stuff for date calcs
         split("JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12", z)
         for (x in z)
         {
            split(z[x],y,":")
            gmonths[y[1]]=y[2]
         }
    }
    

提交回复
热议问题