I am trying to convert incoming date into another format below is the code I have written.
#!/usr/bin/perl
#
use POSIX qw(strftime);
use Date::Manip;
my $string = "Run started at 12:01:48 PM on Aug 19 2016 ";
my @array = split(' ',$string);
$string = "12:01:48 PM Aug 19, 2016";
$unix_time = UnixDate( ParseDate($string), "%s" );
#print $unix_time;
my $datestring = strftime "%a %b %e %H:%M:%S %Y", gmtime($unix_time);
printf("date and time - $datestring\n");
I want the output in Fri Aug 19 12:01:48 2016
but right on PM is not getting considered can you please help me here ?
Have you considered using Time::Piece instead of Date::Manip? It is part of the standard Perl distribution (since Perl 5.10) and is generally considered to be far superior to Date::Manip.
You need to use strptime()
(string parse time) to convert your string to a Time::Piece object and then strftime()
(string format time) to convert your object to a string in the required format.
#!/usr/bin/perl
use strict;
use warnings;
# We use modern Perl - specifically say()
use 5.010;
use Time::Piece;
my $string = '12:01:48 PM Aug 19, 2016';
my $tp = Time::Piece->strptime($string, '%H:%M:%S %p %b %d, %Y');
say $tp->strftime('%a %b %e %H:%M:%S %Y');
Update: And to answer your original question, I think you're getting burnt by time zones. It seems that ParseDate()
assumes that the string is in the local time zone - but you're using gmtime()
to generate your new date string. If you switch that to localtime()
you will get the answer you want.