vkk05
vkk05

Reputation: 3222

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).

Upvotes: 0

Views: 230

Answers (2)

ikegami
ikegami

Reputation: 386706

Here are a few alternatives that will do quite nicely:

my $output =
    sprintf "%s-%s-%s-%s:%s:%s",
       unpack 'a4 a2 a2 a2 a2 a2',
          $input;

my $output = $input =~ s/^(....)(..)(..)(..)(..)(..)\z/$1-$2-$3-$4:$5:$6/sr;

my $output = $input =~ /^(....)(..)(..)(..)(..)(..)\z/s
  ? "$1-$2-$3-$4:$5:$6"
  : die("Bad input\n");

Upvotes: 2

Grinnz
Grinnz

Reputation: 9231

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";

Upvotes: 1

Related Questions