Why is there a difference with Unix date between 2 and 3 months

Shirker asked:

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'
[root@web000c zfs_test]# date +%y-%m-%d --date='3 months ago'
[root@web000c zfs_test]# date
Sun Jun  1 00:08:50 CEST 2014

My 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"

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.