Search code examples
perldatetimelocaltime

Perl convert datetime with pm to gmtime


I get a database date in a variable an need to convert the date from 12h to 24h format.

For instance, the date Jun 19 2019 11:08pm should be converted to Jun 19 2019 23:08.

Here is my unsuccessful attempt:

#!/usr/bin/perl 
use strict; 
use warnings; 
use feature 'say'; 
use Time::Piece; 

my $date="Jun 19 2019 11:08pm"; 
for (qw[$date]) { 
    my $time = Time::Piece->strptime($_, '%H%p'); 
    say $time->strftime('%H:%M:%S'); 
}

Solution

  • use strict;
    use warnings;
    use feature 'say';
    
    use Time::Piece;
    
    my $date="Jun 19 2019 11:08pm";
    
    # strptime %I:%M%p matches 12-hour with am/pm
    # strftime %H converts to 24-hour
    $date = Time::Piece->strptime($date, '%b %d %Y %I:%M%p')->strftime('%b %d %Y %H:%M');
    
    say $date;
    
    # Jun 19 2019 23:08