There were many occasions when I had to find out something like "one week after current date" or "one month and two days earlier", something like that. All this lead me to searching for 'date mathematics' in bash. And here is the result I found. (Warning: this may not work in older systems)
This is achieved using the -d option of date which has a syntax:
date -d STRING
where string defines, the format of date. Here is were you can implement date math. As you can see below:
safeer@enjoyfast-lx:~$ date
Wed Dec 3 00:11:06 IST 2008
Now find tomorrows date - just use "+1 day" as format string
safeer@enjoyfast-lx:~$ date -d "+1 day"
Thu Dec 4 00:11:07 IST 2008
So the general format of the string is "+/-N UNIT" where UNIT is any one of "second|minute|hour|day|week|month|year" and N is the number of units. + or - sign determines whether to add or subtract a date. A few examples:
15 hours after current time:
safeer@enjoyfast-lx:~$ date;date -d "+15 hour"
Wed Dec 3 00:14:32 IST 2008
Wed Dec 3 15:14:32 IST 2008
3 months earlier:
safeer@enjoyfast-lx:~$ date;date -d "-3 months"
Wed Dec 3 00:18:39 IST 2008
Wed Sep 3 00:18:39 IST 2008
You can also combine different units as needed:
safeer@enjoyfast-lx:~$ date;date -d "+15 week -2 hours"
Wed Dec 3 00:21:21 IST 2008
Tue Mar 17 22:21:21 IST 2009
This way we can get whatever date we need. Combining this with the output formating option for date will give you good formatted dates to use in your scripts and commands. For eg:
safeer@enjoyfast-lx:~$ date -d "-2 year +42 hours"
Mon Dec 4 18:23:22 IST 2006
safeer@enjoyfast-lx:~$ date -d "-2 year +42 hours" +%F
2006-12-04
Very helpful. Thank you - Clay Mitchell, San Francisco, CA
ReplyDeleteCan’t find if two dates are on the same day that way.
ReplyDeleteSure you can:
Delete$ echo $(( $(date -d 2014/9/5 +%u) - $(date -d 2014/9/12 +%u) ))
0
$ echo $(( $(date -d 2014/9/6 +%u) - $(date -d 2014/9/12 +%u) ))
1
$ [[ $(date -d 2014/9/5 +%a) == $(date -d 2014/9/12 +%a) ]] && echo yes || echo no
yes
$ [[ $(date -d 2014/9/6 +%a) == $(date -d 2014/9/12 +%a) ]] && echo yes || echo no
no