Bash: date -d 1 month ago still shows the same month

Written by - 0 comments

Published on - Listed in Linux Shell Bash Coding


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.

RSS feed

Blog Tags:

  AWS   Android   Ansible   Apache   Apple   Atlassian   BSD   Backup   Bash   Bluecoat   CMS   Chef   Cloud   Coding   Consul   Containers   CouchDB   DB   DNS   Database   Databases   Docker   ELK   Elasticsearch   Filebeat   FreeBSD   Galera   Git   GlusterFS   Grafana   Graphics   HAProxy   HTML   Hacks   Hardware   Icinga   Influx   Internet   Java   KVM   Kibana   Kodi   Kubernetes   LVM   LXC   Linux   Logstash   Mac   Macintosh   Mail   MariaDB   Minio   MongoDB   Monitoring   Multimedia   MySQL   NFS   Nagios   Network   Nginx   OSSEC   OTRS   Office   OpenSearch   PGSQL   PHP   Perl   Personal   PostgreSQL   Postgres   PowerDNS   Proxmox   Proxy   Python   Rancher   Rant   Redis   Roundcube   SSL   Samba   Seafile   Security   Shell   SmartOS   Solaris   Surveillance   Systemd   TLS   Tomcat   Ubuntu   Unix   VMWare   VMware   Varnish   Virtualization   Windows   Wireless   Wordpress   Wyse   ZFS   Zoneminder