2010-10-26

Roll your own "datetime" command line tool in Mac OS X

Sometimes you need the current date and time as a string. Perhaps to copy paste, or label something.

Mac OS X does have a command line tool to generate such a string, called: date

Unfortunately, the date string returned by default is the old-fashioned style:

Tue Oct 26 17:25:19 PDT 2010

All the cool kids nowadays are using ISO 8601, in a style such as YYYY-MM-DD HH:MM:SS
You can temporarily get your Terminal window to do this by pasting: alias datetime='date "+%Y-%m-%d %H:%M:%S"' and then typing: datetime


When you close that Terminal window, your Mac will forget all about this alias. To make it remember, create a text file named exactly, saved to your home folder: .bash_profile


'bash' is the name of the Unix shell used by default in later versions of Mac OS X. The period in front makes this file disappear, that is, the Finder will ignore it. There are other places to save this "alias" command, other files and folders, both traditional Unix/bash ways and Mac-specific ways. This way works for me.

The Terminal is built to look for and open a file with that exact name every time you open a Terminal window. Windows already open will not be updated, so try your new "datetime" command in a new window. You should see something like this:
2010-10-26 17:34:01

You can vary that alias, or create others, if you like. 
  • If you want to use this datetime as part of the name for a file in the Mac's HFS+ file system, then you must avoid the colons.
    alias datetime_mac='date "+%Y-%m-%d %H-%M-%S"'

  • A strict ISO 8601 datetime should have a "T" rather than a space in the middle, and represents the time zone as an offset from UTC time.
    alias datetime_iso='date "+%Y-%m-%dT%H:%M:%S%z"'

  • You may want to use UTC time (formerly known as GMT or Greenwich Mean Time), where 'Z' means Zulu time.
    alias datetime_utc='date -u "+%Y-%m-%d %H-%M-%SZ"'

  • Perhaps UTC time in ISO format:
    alias datetime_utc_iso='date -u "+%Y-%m-%dT%H:%M:%SZ"'
For your convenience, here is all 5 ready for cut-and-paste:


alias datetime='date "+%Y-%m-%d %H:%M:%S"'
alias datetime_mac='date "+%Y-%m-%d %H-%M-%S"'
alias datetime_iso='date "+%Y-%m-%dT%H:%M:%S%z"'
alias datetime_utc='date -u "+%Y-%m-%d %H:%M:%SZ"'
alias datetime_utc_iso='date -u "+%Y-%m-%dT%H:%M:%SZ"'


Results:

$ datetime
2010-10-26 18:11:59


$ datetime_mac
2010-10-26 18-12-03


$ datetime_iso

2010-10-26T18:12:06-0700

$ datetime_utc
2010-10-27 01:12:13Z


$ datetime_utc_iso
2010-10-27T01:12:19Z


No comments:

Post a Comment