Often times, when working with the standard Linux/UNIX time format (time_t) one needs to quickly find out what is the “human readable” date and time text string a particular time_t value corresponds to.

NOTE: The ‘C’ time_t type is the number of seconds elapsed since the “epoch”, the epoch being January 1st 1970 at 00:00:00.

As much as I tried to find a standard *NIX command to do the job I couldn’t.. Eventually I wrote a C two-liner to do the job but I am still curious if there is a standard shell command to do the job, so if anybody knows of one I would appreciate a comment… πŸ™‚

As far as writing it yourself this line of code will do the job :
printf("UNIX time %ld is: %s\n", time_t_var, ctime( &time_t_var ) );
, where the variable time_t_var holds the time_t value…

Because ctime is used to convert time_t into a datetime text string, the text will display the date and time taking into account the current locale settings (timezone and summer time). If you want a ‘raw’ UTC/GMT representation of the time_t value then use gmtime()..

An example using both functions follows:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main(int argc, char **argv)
    time_t  time_t_var;

    if (argc > 1)
        time_t_var = atoi(argv[1]);
        time_t_var = time((time_t *) NULL);

    printf( "UNIX time %ld is: %s (ctime)\n",
            time_t_var, ctime( &time_t_var ) );

    struct tm tm_val;
    gmtime_r( &time_t_var, &tm_val );
    printf( "UNIX time %ld is: %s (gmtime)\n",
            time_t_var, asctime(&tm_val) );

    return 0;

3 Responses to Convert UNIX time_t into a date/time text string

  1. Tom Swiss says:

    It’s slightly arcane, but in the shell you can use the ‘date’ command to translate to and from time_t, like so:

    % date –date=’2014-10-24 6:52pm utc’ ‘+%s’

    % date –date=’1970-01-01 UTC 1414176720 seconds’ +”%Y-%m-%d %T %z”
    2014-10-24 14:52:00 -0400

    • ench0 says:

      Hi Tom

      Thanks for your suggestion. It did not work for me in this exact format which you suggested, probably due to different date util versions requiring slightly different syntax or somth similar (my date util is ver 8.10 )… anyway I fugured it out. πŸ™‚

      This did the trick for me:

      # date --utc --date="2014-10-24 6:52pm" "+%s"

      Awesome – thanks again for your tip!

      Note: I bet there was a before the date param in your post as well but wordpress seems to get rid of it in the comments, converting it into a single -. I had to enclose each of the two dashes in my comment within a HTML ‘bold’ marker to make them appear as a double dash πŸ˜‰

  2. ench0 says:

    And to solve the reverse problem you may use:

    $ date -d @1388534400
    Wed Jan 1 02:00:00 EET 2014

Leave a Reply

Your email address will not be published. Required fields are marked *

Set your Twitter account name in your settings to use the TwitterBar Section.