A gentle introduction to using DateTime in Perl
Working with dates in Perl is very easy thanks to the DateTime
module. In this article we’ll show you how to install the module, determine which of two dates is the latest in Perl, and some other date and time tips and tricks along the way.
DateTime
in Perl
First, if you haven’t already install Perl. On ArchLinux you can do this with
$ sudo pacman -S perl
For other systems consult https://www.perl.org/get.html
Then install DateTime
with
$ cpan DateTime
You might first have to run just $cpan
in order to configure cpan
for the first time.
DateTime
ObjectsThere’s a few different ways to make DateTime
objects
We can make them from the system time, which includes the current time zone information.
1use DateTime;
2
3my $dt = DateTime->now;
4print "Current date and time: ", $dt, "\n";
We can also make a specific date and time
1use DateTime;
2
3my $dt = DateTime->new(
4 year => 2023,
5 month => 12,
6 day => 25,
7 hour => 10,
8 minute => 30,
9 second => 0,
10);
11print "Specific date: ", $dt, "\n";
Alternatively we can parse an ISO 8601 date string
1use DateTime;
2
3my $dt = DateTime::Format::ISO8601->parse_datetime('2023-12-25T10:30:00Z');
4print "Parsed ISO 8601 date: ", $dt, "\n";
You may need to install ISO8601 for this to work
$ cpan install DateTime::Format::ISO8601
DateTime
ObjectsComparing DateTime
objects and determining which date is latest in Perl is thankfully very easy.
The following example illustrates comparisons
1use strict;
2use warnings;
3use DateTime;
4
5
6my $dt1 = DateTime->now;
7
8my $dt2 = DateTime->new(
9 year => 2023,
10 month => 12,
11 day => 25,
12 hour => 10,
13 minute => 30,
14 second => 0,
15);
16
17if ($dt1 < $dt2) {
18 print $dt1, " is older than ", $dt2, "\n";
19} elsif ($dt1 > $dt2) {
20 print $dt1, " is newer than ", $dt2, "\n";
21} else {
22 print "Dates are the same\n";
23}
DateTime
While the default printing of DateTime
as in the above examples usually works, sometimes we might want to customise the display options. We can do this by using strftime
1my $dt = DateTime->now;
2my $formatted_date = $dt->strftime('%Y-%m-%d %H:%M:%S');
3print "Formatted date: $formatted_date\n";
As you can see, working with dates in Perl is very easy. Now you know how to install DateTime, make a DateTime object, determine which date is newer and customise the printing of date objects.