perlepoch

Full manual conversion of Epoch time to Date and Time


I wrote this Perl script to convert date and time from files into epoch time.

The original date format is dd-mm-yyyy hh:MM:ss

The reason I do this is because I have to write these values to a database and only integer values are accepted by the columns.

use strict;
use warnings;
use Time::Local;

$datestring = '07-06-2019 21:13:00';

my ($dd, $mm, $yyyy, $hh, $min, $sec) = split /\W+/, $datestring;

my $epoch = timelocal($sec,$min,$hh,$dd,$mm-1,$yyyy-1900);
print("$epoch\n");

Which translates the date 07-06-2019 21:13:00 to 1559934780

The issue: The values are now presented in a front-end which is unreadable by the user, the front-end does not have scripting utilities and I can only use numerous different calculation formulas which I can use to make it readable.

Is there a completely manual method, by simply using a calculator/calculation to translate epoch time back into user readable date and time?


Solution

  • The core Time::Piece can convert in both directions simply for your local time zone.

    use strict;
    use warnings;
    use Time::Piece;
    
    my $datestring = '07-06-2019 21:13:00';
    my $time = localtime->strptime($datestring, '%d-%m-%Y %H:%M:%S');
    my $epoch = $time->epoch;
    
    ...
    
    my $time = localtime($epoch);
    my $datestring = $time->strftime('%d-%m-%Y %H:%M:%S');
    

    See any standard strftime or strptime man page for the format specifiers that are usually accepted - unfortunately the ones Time::Piece accepts are not documented.


    Without access to Time::Piece, which is core since Perl 5.10, you can use the built in localtime function, it's just a little more complicated (like timelocal).

    use strict;
    use warnings;
    my $epoch = 1559934780;
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime $epoch;
    my $date_string = sprintf '%02d-%02d-%04d %02d:%02d:%02d',
      $mday, $mon+1, $year+1900, $hour, $min, $sec;