Search code examples
linuxbashepoch

Getting human readable date from Epoch into variable


Okay, this is probably a very basic question; but, I'm just getting back in the saddle with Linux.

I have a variable that hold an Epoch time called pauseTime. I need that variable to become human readable (something like 2012-06-13 13:48:30).

I know I can just type in

date -d @133986838 //just a random number there

and that will print something similar. But I need to get the variable to hold that human readable date, instead of the epoch time... I keep running into errors with everything I'm trying. Any thoughts on how I can do this?


Solution

  • Well do this:

    VARIABLENAME=$(date -d @133986838)
    

    and then

    export VARIABLENAME
    

    or in Bash do directly:

    export VARIABLENAME=$(date -d @133986838)
    

    If you want formatting, say in the usual ISO format:

    export ISODATE=$(date -d @133986838 +"%Y-%m-%d %H:%M:%S")
    # or
    EPOCHDATE=133986838
    export ISODATE=$(date -d @$EPOCHDATE +"%Y-%m-%d %H:%M:%S")
    

    The formats behind the + are explained in man date.

    Note: $() is the modern form of the backticks. I.e. catching output from a command into a variable. However, $() makes some things easier, most notably escaping rules inside of it. So you should always prefer it over backticks if your shell understands it.