暗无天日

=============>DarkSun的个人博客

使用date进行日期之间的计算

很早就知道date命令的 --date 参数可以让date命令按照指定的时间来显示结果, 但是我没有想到的是 --date 参数居然支持进行时间的加减运算!

下面这段说明摘自 man date

DATE STRING
       The --date=STRING is a mostly free format human readable date string such as "Sun, 29 Feb 2004 16:21:42  -0800"
       or  "2004-02-29  16:21:42"  or even "next Thursday".  A date string may contain items indicating calendar date,
       time of day, time zone, day of week, relative time, relative date, and numbers.  An empty string indicates  the
       beginning  of  the  day.   The  date  string format is more complex than is easily documented here but is fully
       described in the info documentation.

换句话说,我们可以用它来进行日期间的加减运算,下面是一些例子:

  1. 计算2018年11月22日再过60天是什么时候

    date --date '2018-11-22 + 60 days' +'%Y-%m-%d'
    
    2019-01-21
    
  2. 计算2018年11月22日,前50天是什么时候

    date --date '2018-11-22 - 50 days' +'%Y-%m-%d'
    
    2018-10-03
    
  3. 还可以加上时分秒

    date --date '2018-11-22 01:02:03 HKT +12 days +12 hours +15 minutes'
    
    2018年 12月 04日 星期二 13:17:03 HKT