Reputation: 187
I have to convert the GMT date to region specific date with format like "YYYY-MM-DD H:M:S". Code developed is :-
use Time::Local;
($year,$mon,$day) = split /\-/, $ARGV[0];
($hrs,$min,$sec ) = split /:/, $ARGV[1];
$time = timegm( $sec, $min, $hrs, $day, $mon-1, $year-1900);
print scalar localtime($time), "\n";
But when I run it like :-
$ perl testDateGMTToLocal.pl 2018-10-29 11:49:33
It gives o/p converted in local time zone:-
Mon Oct 29 07:49:33 2018
But I want this o/p in below format
29-OCT-18 07:49:33
Thanks in advance.
Upvotes: 2
Views: 165
Reputation: 66883
I'd recommend to do it all using modules. The all-capable and very complete module is DateTime, and for this job you'd also need DateTime::Format::Strptime.
One other option is the simpler and much smaller core module Time::Piece
use warnings;
use strict;
use feature 'say';
use Time::Piece;
die "Usage $0 YYYY-MM-DD H:M:S" if @ARGV != 2;
my $time = join ' ', @ARGV;
my $tp = Time::Piece->strptime($time, "%Y-%m-%d %T");
my $local = localtime($tp->epoch);
say $local;
# In the desired format
say join('-', $local->mday, uc $local->month, $local->yy),
' ', $local->hms;
# If "Oct" is ok instead of block capitals for month abbreviation
say $local->strftime("%d-%b-%y %T");
This converts GMT time, with invocation as in the question, to the local time on my machine
Mon Oct 29 04:09:33 2018 29-OCT-18 04:09:33 29-Oct-18 04:09:33
where the middle one was asked for.
On some systems there is the %F
format specifier for %Y-%m-$d
.† There may be a defined format for 29-OCT-18
, in which case you don't have to patch it by hand, but I am not aware of it.
† Or the module has its own formatting in which case that's portable. But origin of the error when it fails to do %F
on my system isn't clear to me in that sense.
Upvotes: 3
Reputation: 385657
You can use
use POSIX qw( strftime );
print(strftime("%d-%b-%y %H:%M:%S", localtime($time)), "\n");
Upvotes: 1