Linux Date Problem – 1 month ago date bug

By | April 1, 2016
Linux Date Problem - 1 month ago date bug

Linux Date Problem – 1 month ago date bug

Linux Date Problem – 1 month ago date bug

There exists what I call the 1 month ago date bug in the GNU date command which (i believe) is on almost every unix distribution that System Admins should at least be aware of.

The date command is frequently used in bash scripts, and in cron scheduled tasks, to calculate dates in the past or future, to reformat dates into different country standards, or using its many features including seeing and using the Epoch date (number of seconds since 1st January 1970).

This post is going to show you a bug for a fairly common use of the date command which is to find the previous month. This sort of thing is useful for month end reporting, or history charts maybe.

So here is the command you would use –

date -d '1 month ago' +%Y-%m

In that example it will show me the CCYY (2016 as example), and MM (today is 1st april, therefore will show 03 for March)

All perfectly normal so far… until you run it on the 31st March (as I did last night)

-bash-4.1$ date
Thu Mar 31 14:34:23 EDT 2016
-bash-4.1$ date -d '1 month ago' +%Y-%m
2016-03
-bash-4.1$

So you see your ‘1 month ago’ is still showing the same month (March), when you expected to see February.

A little bit more investigation instead of just displaying CCYY-MM and showing the whole date it shows ‘1 month ago’ as being 2nd March. That is 29 days ago, suggesting it knows the previous month was February, it also knows in 2016 that February had 29 days in it (leap year), and took current date – 29 to get 1 month ago. Now therefore, you can see the 1 month ago date BUG !!!

Check out -  Upgrade Plex Media Server (Centos, Ubuntu, Fedora)

So how to get around it?

The Solution

Well for my purposes I simply wanted the month, therefore an easy solution is this –

date -d "$(date +%Y-%m-15) -1 month" +%Y-%m

will display me 2016-02.

What this does is to take the current month, use a static date for that current month to be the 15th (therefore avoiding varying number of days in a month), and then looking for the previous month.

I would like to thank Paul Rieber for this, as he encountered the same issue previously and answered my question on Quora (I think) with the clearest answer, and neatest solution to something that is not just related to Centos but many distributions of Linux.

BE AWARE OF THE '1 month ago' DATE BUG

So this is just to make sure every System Admin is at least aware of the bug before it bites them.

Share this post with all your System Admin friends !!

Check out -  MySQL get list of Wordpress tags for a specific post

Leave a Reply