Unix Date Difference Between 2 and 3 Months Explained

command-line-interfacedate

How is this possible and how do I deal with it? I'm making backup script that is dependent on Unix date and have discovered an interesting bug:

[root@web000c zfs_test]# date +%y-%m-%d --date='2 months ago'
14-04-01
[root@web000c zfs_test]# date +%y-%m-%d --date='3 months ago'
14-02-28
[root@web000c zfs_test]# date
Sun Jun  1 00:08:50 CEST 2014

Best Answer

You're seeing this behavior because of summer time (daylight saving time).

Because you are currently in summer time, where your clock is one hour ahead, when you ask for three months ago at just after midnight on the first of June, the time ends up being one hour "earlier" because it was not summer time three months ago.

The GNU date documentation suggests to work around this by using 12:00 noon and the 15th of the month as starting points, when asking for relative days or months, respectively. For example:

date +%y-%m-%d --date="$(date +%Y-%m-15) -3 month"
Related Topic