Convert 12-hour date/time to 24-hour date/time

Using Perl and hand-crafted regexes instead of facilities like strptime:

#!/bin/perl -w
while (<>)
{
    # for date times that don't use leading zeroes, use this regex instead:
    # (?:\d{1,2}/\d{1,2}/\d{4} )(\d{1,2})(?::\d\d:\d\d) (AM|PM)
    while (m%(?:\d\d/\d\d/\d{4} )(\d\d)(?::\d\d:\d\d) (AM|PM)%)
    {
        my $hh = $1;
        $hh -= 12 if ($2 eq 'AM' && $hh == 12);
        $hh += 12 if ($2 eq 'PM' && $hh != 12);
        $hh = sprintf "%02d", $hh;
        # for date times that don't use leading zeroes, use this regex instead:
        # (\d{1,2}/\d{1,2}/\d{4} )(\d{1,2})(:\d\d:\d\d) (?:AM|PM)
        s%(\d\d/\d\d/\d{4} )(\d\d)(:\d\d:\d\d) (?:AM|PM)%$1$hh$3%;
    }
    print;
}

That’s very fussy – but also converts possibly multiple timestamps per line.

Note that the transformation for AM/PM to 24-hour is not trivial.

  • 12:01 AM –> 00:01
  • 12:01 PM –> 12:01
  • 01:30 AM –> 01:30
  • 01:30 PM –> 13:30

Now tested:

perl ampm-24hr.pl <<!
12/24/2005 12:01:00 AM
09/22/1999 12:00:00 PM
12/12/2005 01:15:00 PM
01/01/2009 01:56:45 AM
12/30/2009 10:00:00 PM
12/30/2009 10:00:00 AM
!

12/24/2005 00:01:00
09/22/1999 12:00:00
12/12/2005 13:15:00
01/01/2009 01:56:45
12/30/2009 22:00:00
12/30/2009 10:00:00

Added:

In What is a Simple Way to Convert Between an AM/PM Time and 24 hour Time in JavaScript, an alternative algorithm is provided for the conversion:

$hh = ($1 % 12) + (($2 eq 'AM') ? 0 : 12);

Just one test…probably neater.

Leave a Comment