Determine which date is latest in perl

Author - Indigo Curnick

October 10, 2024
Articles

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.

Installing 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.

Making DateTime Objects

There’s a few different ways to make DateTime objects

We can make them from the system time, which includes the current time zone information.

use DateTime;

my $dt = DateTime->now;
print "Current date and time: ", $dt, "\n";

We can also make a specific date and time

use DateTime;

my $dt = DateTime->new(
    year   => 2023,
    month  => 12,
    day    => 25,
    hour   => 10,
    minute => 30,
    second => 0,
);
print "Specific date: ", $dt, "\n";

Alternatively we can parse an ISO 8601 date string

use DateTime;

my $dt = DateTime::Format::ISO8601->parse_datetime('2023-12-25T10:30:00Z');
print "Parsed ISO 8601 date: ", $dt, "\n";

You may need to install ISO8601 for this to work

$ cpan install DateTime::Format::ISO8601

Comparing DateTime Objects

Comparing DateTime objects and determining which date is latest in Perl is thankfully very easy.

The following example illustrates comparisons

use strict;
use warnings;
use DateTime;


my $dt1 = DateTime->now;

my $dt2 = DateTime->new(
    year   => 2023,
    month  => 12,
    day    => 25,
    hour   => 10,
    minute => 30,
    second => 0,
);

if ($dt1 < $dt2) {
    print $dt1, " is older than ", $dt2, "\n";
} elsif ($dt1 > $dt2) {
    print $dt1, " is newer than ", $dt2, "\n";
} else {
    print "Dates are the same\n";
}

Custom Display of 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

my $dt = DateTime->now;
my $formatted_date = $dt->strftime('%Y-%m-%d %H:%M:%S');
print "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.

Subscribe To Our Newsletter - Sleek X Webflow Template

Subscribe to our newsletter

Sign up at Naurt for product updates, and stay in the loop!

Thanks for subscribing to our newsletter
Oops! Something went wrong while submitting the form.