views:

256

answers:

6

I need a shell command or script that converts a UNIX timestamp to a date. The input can come either from the first parameter or from stdin, allowing for the following usage patterns:

ts2date 1267619929

and

echo 1267619929 | ts2date

Both commands should output "Wed Mar 3 13:38:49 2010".

A: 

I have written a script that does this myself:

#!/bin/bash
LANG=C
if [ -z "$1" ]; then
    if [  "$(tty)" = "not a tty" ]; then
            p=`cat`;
    else
            echo "No timestamp given."
            exit
    fi
else
    p=$1
fi
echo $p | gawk '{ print strftime("%c", $0); }'
chiborg
Your question tags include "bash", but your shebang says "sh".
Dennis Williamson
Thanks, fixed it.
chiborg
A: 

In PHP

$unix_time = 1256571985;

echo date("Y-m-d H:i:s",$unix_time)
Lucas
Nice, but I just wanted to use bash.
chiborg
A: 

You can use this simple awk script:

#!/bin/gawk -f   
{ print strftime("%c", $0); }

Sample usage:

$ echo '1098181096' | ./a.awk 
Tue 19 Oct 2004 03:18:16 AM PDT
$
codaddict
This doesn't fit the first usage - sometimes I don't want to echo the TS and use a parameter instead.
chiborg
+4  A: 

On later versions of common Linux distributions you can use:

date -d @1267619929
ar
+1  A: 

you can use GNU date eg

$ sec=1267619929
$ date -d "UTC 1970-01-01 $sec secs"

or

$ date -ud @$sec
ghostdog74
+2  A: 

This version is similar to chiborg's answer, but it eliminates the need for the external tty and cat. It uses date, but could just as easily use gawk. You can change the shebang and replace the double square brackets with single ones and this will also run in sh.

#!/bin/bash
LANG=C
if [[ -z "$1" ]]
then
    if [[ -p /dev/stdin ]]    # input from a pipe
    then
        read -r p
    else
        echo "No timestamp given." >&2
        exit
    fi
else
    p=$1
fi
date -d @$p +%c
Dennis Williamson
+1: very complete answer and I think date is faster than gawk.
Bruno Brant
@Bruno, how do you know date is faster than gawk.?
ghostdog74
@Bruno, @ghostdog74: On my system, `gawk` is (very roughly) 15% faster than `date` in a timed `for` loop consisting only of `gawk 'BEGIN { print strftime("%c", 1256571985); }'` or `date -d '@1256571985' +%c` with output redirected to `/dev/null`.
Dennis Williamson
I chose this as the "best" answer because the script satisfies the "date input via parameter or stdin" better. Thanks for enhancing my shellscripting skills!
chiborg