GNU date luxuries

http://www.cyberciti.biz/tips/linux-unix-get-yesterdays-tomorrows-date.html

Has a pretty good summary of using GNU date’s strtotime implementation.

strtotime.y is an interesting piece of code. Its often reproduced and imitated. The header says

Originally written by Steven M. Bellovin <smb@research.att.com> while at the University of North Carolina at Chapel Hill.  Later tweaked by a couple of people on Usenet.  Completely overhauled by Rich $alz <rsalz@bbn.com> and Jim Berets <jberets@bbn.com> in August, 1990;

This grammar has 13 shift/reduce conflicts.

This code is in the public domain and has no copyright.

Thanks Steven!

It turns out GNU renames this to parse-datetime.y, and fixes some local DST issues, but you can see that original message still there.

Its a nice lex/yacc refresher when you have been away from those tools for a while, and a nice C refresher too. Using it is easier than understanding how it works.

One of the things I like is that you can combine expressions.

$ date -d ‘1 day ago’
Wed May 14 15:11:51 UTC 2014

Just leave out the english conjunction. So instead of 1 day ago and 2 hours ago, say 1 day ago 2 hours ago.

$ date -d ‘1 day ago 2 hours ago’
Wed May 14 13:12:00 UTC 2014

I should mention that these are correct, because the time right now is

$ date
Thu May 15 15:12:50 UTC 2014

One thing which is not really clear in the above tip page is that minus is just an alias for ago.

$ date -d ‘-1 day -2 hours’
Wed May 14 13:14:04 UTC 2014

Things one may wish to do is floor a result. e.g. making yesterday start at top of yesterday.

$ date -d ‘yesterday 00:00’
Wed May 14 00:00:00 UTC 2014

Finally, I was surprised to dig up ruby’s date_parse.c and find that it does not claim any heritage with the original strtotime.y.

 

update 3 hours later:

I was just doing some comparisons on systems which use strtotime and the question arose, what if I call it with empty string?

$ date -d ”
Thu May 15 00:00:00 UTC 2014

easy answer: its the midnight floor of todays date. The same as ‘now 00:00:00’, ‘now 00:00’, or just ‘now 0’.

 

Update about a year later:

I wanted to know when 6months and 8months after the iPhone 6 release was. I can type a date and the plus operator is implied.

$ date -d 'Sept 19, 2014 6 months'
Thu Mar 19 00:00:00 EDT 2015
$ date -d 'Sept 19, 2014 8 months'
Tue May 19 00:00:00 EDT 2015

Hey! That is today!