Search code examples
perlunix-timestamp

Convert from one date-time format to a different date-time format


I want to convert a time which is taken as an argument to the Perl script into a different format.

The input is of the form yyyyMMddHHmmss (e.g. 20190101235010).

The output should be of of the form yyyy-MM-dd-HH:mm:ss (e.g. 2019-01-01-23:50:10).

It would be better if solution doesn't use Perl Modules (except POSIX).


Solution

  • The core module Time::Piece does this easily.

    use strict;
    use warnings;
    use Time::Piece;
    
    # if input is the format you specified:
    my $input = '20190101235010';
    my $time = Time::Piece->strptime($input, '%Y%m%d%H%M%S');
    print $time->strftime('%Y-%m-%d-%H:%M:%S'), "\n";
    
    # if input is a unix epoch timestamp:
    my $input = time;
    my $time = gmtime $input;
    print $time->strftime('%Y-%m-%d-%H:%M:%S'), "\n";