Time Formatting Parsing in Perl

Perl supports time formatting and parsing via pattern-based layouts.

use strict;
use warnings;
use Time::Piece;
use Time::Seconds;

sub p {
    print "@_\n";
}

# Here's a basic example of formatting a time
# according to RFC3339, using the corresponding layout
# constant.
my $t = localtime;
p($t->strftime('%Y-%m-%dT%H:%M:%S%z'));

# Time parsing uses the same layout values as strftime.
my $t1 = Time::Piece->strptime("2012-11-01T22:08:41+00:00", '%Y-%m-%dT%H:%M:%S%z');
p($t1);

# strftime and strptime use example-based layouts. Usually
# you'll use a constant from Time::Piece for these layouts, but
# you can also supply custom layouts.

p($t->strftime('%I:%M%p'));
p($t->strftime('%a %b %d %H:%M:%S %Y'));
p($t->strftime('%Y-%m-%dT%H:%M:%S.%6N%z'));

my $form = '%I %M %p';
my $t2 = Time::Piece->strptime("8 41 PM", $form);
p($t2);

# For purely numeric representations you can also
# use standard string formatting with the extracted
# components of the time value.
printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
    $t->year, $t->mon, $t->mday,
    $t->hour, $t->min, $t->sec);

# strptime will die on malformed input
# explaining the parsing problem.
eval {
    my $ansic = '%a %b %d %H:%M:%S %Y';
    Time::Piece->strptime("8:41PM", $ansic);
};
p($@);

This Perl script demonstrates time formatting and parsing using the Time::Piece module, which provides an object-oriented interface to Perl’s built-in localtime and gmtime functions.

The script shows how to:

  1. Format the current time using RFC3339 format.
  2. Parse a time string in RFC3339 format.
  3. Use custom format strings for both formatting and parsing.
  4. Extract individual components of a time object for custom formatting.
  5. Handle errors in time parsing.

Note that Perl uses strftime for formatting and strptime for parsing, which are similar in concept to Go’s Format and Parse methods. The format specifiers in Perl follow the POSIX standard, which is different from Go’s example-based layout system.

When you run this script, you’ll see output similar to the following:

2023-06-15T14:30:45+0200
2012-11-01T22:08:41+0000
02:30PM
Thu Jun 15 14:30:45 2023
2023-06-15T14:30:45.123456+0200
Thu Jan  1 20:41:00 1970
2023-06-15T14:30:45-00:00
Error parsing time: Error parsing time at /path/to/script.pl line XX.

The exact output will depend on the current time when you run the script.