Header RSS Feed
 
If you only want to see the articles of a certain category, please click on the desired category below:
ALL Android Backup BSD Database Hacks Hardware Internet Linux Mail MySQL Monitoring Network Personal PHP Proxy Shell Solaris Unix Virtualization VMware Windows Wyse

Bash: date -d 1 month ago still shows the same month
Thursday - Mar 29th 2018 - by - (0 comments)

I'm currently working on an automated way of getting availability stats into a Confluence page (basically my article from 2010 How to create automatic PDF from Nagios Availabilty Reports? but more advanced).

The idea is, so far, to run on the 1st of the month and get the statistics from the previous month (lastmonth). While doing some tests, I came across this:

root@monitoring:~# date
Thu Mar 29 14:00:48 CEST 2018

root@monitoring:~# date -d "1 month ago"
Thu Mar  1 13:00:54 CET 2018

Can you see it? Today is March 29th but the command "date" thinks a month ago was the 1st of March. That's definitely not correct. Without having checked the man page for details, I assume that "1 month ago" is an alias for "4 weeks ago":

root@monitoring:~# date -d "4 weeks ago"
Thu Mar  1 13:03:00 CET 2018

This can be verified manually by checking the calendar:

root@monitoring:~# cal
     March 2018       
Su Mo Tu We Th Fr Sa  
             1  2  3  
 4  5  6  7  8  9 10  
11 12 13 14 15 16 17  
18 19 20 21 22 23 24  
25 26 27 28 29 30 31 

Take the 29th, move up the cursor 4 times and there you arrive on the 1st of March.

Of course I'm not the first one this happens to. I came across a Stackexchange article where the second response mentions dateadd from the "dateutils".
Note: Interestingly the OP selected the first answer "The usual wisdom is use the 15 of this month. Then subtract 1 month" as solution. Which to me is just another workaround, not a real fix.

dateutils can be installed in all major distributions as it has a dedicated package:

root@monitoring:~# apt-get install dateutils

Let's try this newly installed command (dateutils.dadd):

root@monitoring:~# dateutils.dadd today -1mo
2018-02-28

root@monitoring:~# dateutils.dadd today -1mo -f '%Y%m'
201802

That looks much better (and correct)!

 

Add a comment

Show form to leave a comment

Comments (newest first):

No comments yet.

Go to Homepage home
Linux Howtos how to's
Monitoring Plugins monitoring plugins
Links links

Valid HTML 4.01 Transitional
Valid CSS!
[Valid RSS]

7121 Days
until Death of Computers
Why?