Dates. Generally horrible to parse, print and format. Hopefully, this script is not the bad kind of puppy. The most often place I find myself in need of a well formatted date is in a command line shell script.
I can’t seem to remember the eleventy-billion different format combinations that can go into the command line date function. I also can’t remember what year has a leap second, if we (the USA) have changed daylight savings yet again, or if the computer is constantly traveling between timezones. Like many things in this world, I have replaced these problems with a very short shell script which prints the date.
Here is a general rule which I have found applies quite frequently. If its simple, it will probably get done or used. Quality of the function aside, if something reasonable exists to solve a problem, most reasonable people will incorporate the component in standard ways. In short, “new” code is bad; “old” code which has been verified correct, is good.
Without further ranting, here is the script.
#!/bin/sh
if [ $# = "0" ] ; then
`echo date '+%C%y-%m-%d'`
else
`echo date '+%C%y-%m-%d_%H-%M-%S'`
fi
This prints out a simple date if no argument is given; if you toss any random argument to it, it will also print out the time… eg:
[gir]$ ./datetime.sh
2007-05-18
[gir]$ ./datetime.sh show_me_the_time
2007-05-18_22-38-49
[gir]$ ./datetime.sh asdf
2007-05-18_22-38-54
[gir]$ ./datetime.sh 1
2007-05-18_22-38-57
This format is an attempt at a well thought out date string for downstream parsing. You may notice the individual numbers are divided by “-”, and the date from time is divided by “_”. This makes it easy to parse the date back out with other scripts in the future! Its also zero padded numbers, so the 11th character is always a “-”.
It has no slashes, which might be misconstrued as directories or escape characters. The reason the date format does not contain spaces, is because it would need to be escaped. Finally, with this method, file names or other items utilizing this date format will sort lexicographically in chronological order.
Now obviously, this just prints out the unix local time. If your computer clock is not set to UTC, then you should add a -u after each of the date commands on each side of the branch. use UTC whenever possible to avoid daylight savings headaches.
Improvements
One improvement I would make (upon reviewing this article a few months later) is to include Epoch time. Epoch time is current number of seconds from January 1, 1970. This is just a big integer, and it doesn’t care about our silly date conventions or timezones. It ignores days, months, years, and everything else which can clog up the works. If you put it at the beginning of the string, one gets a very nice sortable list. It is also easy to create code later which translates Epoch time to PST, GMT, or whatever else you would like!

