How to get a formatted date for a UNIX timestamp from the command line

command line

I have a UNIX timestamp and I'd like to get a formatted date (like the output of date) corresponding to that timestamp.

My attempts so far:

$ date +%s
1282367908
$ date -d 1282367908
date: invalid date `1282367908'
$ date -d +1282367908
date: invalid date `+1282367908'
$ date +%s -d +1282367908
date: invalid date `+1282367908'

I'd like to be able to get output like:

$ TZ=UTC somecommand 1282368345
Sat Aug 21 05:25:45 UTC 2010

Best Answer

On Mac OS X and BSD:

$ date -r 1282368345
Sat Aug 21 07:25:45 CEST 2010
$ date -r 1282368345 +%Y-%m-%d
2010-08-21

with GNU core tools (you have to dig through the info file for that):

$ date -d @1282368345
Sat Aug 21 07:25:45 CEST 2010
$ date -d @1282368345 --rfc-3339=date
2010-08-21

With either, add the -u (standard) option, or pass a TZ=UTC0 environment variable to have the UTC date (TZ=UTC0 defines a timezone called UTC with offset 0 from UTC while the behaviour for TZ=UTC (with no offset) is unspecified (though on most systems would refer to a system-defined timezone also called UTC with offset 0 from UTC)).