Shell Scripting: How to easily convert UNIX timestamp into date format

Posted by: admin  :  Category: Perl, Programming, Scripting

When writing shell scripts (bash, sh, etc) maybe you had to work with POSIX/UNIX timestamps from time to time.
While the serialized nature of the timestamp is great to work with for scripting, it’s easier for human beings to have them printed in date format.

Before you start digging around using some fancy conversion in Perl, check out the ‘date’ command first.

Here’s a little snippet on how to do it on Linux:

date -u --date="1970-01-01 1285250916 sec GMT"

This will convert your timestamp 1285250916 into it’s date representation of Thu Sep 23 14:08:36 UTC 2010.

As always, there’s slight variations with Linux and BSD userland. To achieve the same on OS X and FreeBSD (maybe other BSDs as well), here’s the appropriate command:

date -j -f %s 1285250916

And for Perl lovers anyway, here is the Perl command 😉

perl -e "print scalar localtime (1285250916)"

As such it’s very easy to capture the output using backticks and use it further on in your scripts. The date command comes in as a last resort especially if you’re working in a restricted environment where higher level languages such as Perl may be unavailable. Though one notices Perl is more versatile than the date command – the later having slight syntactical variations between distributions and vendors propably causing some headache. This opts for the use of Perl if you want to be more platform independent with your script.

4 Responses to “Shell Scripting: How to easily convert UNIX timestamp into date format”

  1. Satchel Says:

    Thanks alot – your answer solved all my pobrelms after several days struggling

  2. Alteran Says:

    I consider this one an easier option:

  3. gdelmatto Says:

    Indeed, if you just want an easy way to convert one or a just few time/date values, then the tool at is just great.

    The article describes however describes conversion on the command line, which is primarily intended to be used within a shell script, so to speak “programmatically” instead “by hand” 😉

  4. Hugh Betcha Says:

    And you can get UTC/GMT from Perl by using gmtime() instead of localtime().