Ps-kl
Ps-kl

Reputation: 127

correct approach to compare dates (in string format) using perl script

i am new to perl scripting. can you please help to compare two date. i have

my $dt1 = "20171026";
my $dt2 = "20180101";

i am using the below snippet to compare dates, however i am not sure if this is the right way

use strict; use warnings;

my $dt1 = "20171026";
my $dt2 = "20180101";
if ($dt1 > $dt2){
    print "Hi";
}
else {
print "hello";
}

can anyone please suggest me if i can format a string say $dt1 to date time format and compare?

Upvotes: 0

Views: 1578

Answers (3)

zdim
zdim

Reputation: 66964

One can compare strings with dates in such format, as explained, but that's all you can do.

There are of course libraries for date-time work, as I think the question asks.

The most comprehensive one is DateTime, which is extremely rounded in functionality

use DateTime::Format::Strptime;

my $format = DateTime::Format::Strptime->new( pattern => '%y%m%d' );
my $dt1 = $format->parse_datetime($dt1_str);
my $dt2 = $format->parse_datetime($dt2_str);

if ($dt1 < $dt2) { say $dt1->ymd, " is earlier than ", $dt2->ymd }

Now you can do all kinds of things with those dates, see documentation.

If you don't need all that much to do and would prefer a far lighter module, there is Time::Piece

use Time::Piece;

my $dt1 = Time::Piece->strptime($dt1_str, "%Y%m%d");
my $dt2 = Time::Piece->strptime($dt2_str, "%Y%m%d");

if ($dt1 < $dt2) { say $dt1->ymd, " is earlier than ", $dt2->ymd }

which is also simpler to use, for simple things. It comes with a few other conveniences, but if your needs grow more complex be careful as some of the module's interfaces can be tricky.

Upvotes: 0

simbabque
simbabque

Reputation: 54381

Your comparison is fine.

Since your dates are really just numbers, and they are in YMD format, a numerical comparison work. The components of the date are sorted by their importance, which is key here.

  • Year first: 2017 is always before 2018
  • Month second: October (10) is later than January (01), but the leading zero is important
  • Day: same thing, 05 would be before 29

So to compare

  • 20170101 is before 20170102
  • 20180101 is after 20171231

because it's all just numbers.

For this format there is absolutely no need or benefit from using a date module and parsing the strings. It will not make it easier to read, nor faster. It will just increase the complexity of your code.

Upvotes: 2

choroba
choroba

Reputation: 242383

If you use the YYYYMMDD (or %Y%m%d) format, you can compare the dates as numbers or strings. It means both

$dt1 > $dt2

and

$dt1 gt $dt2

work correctly. I prefer to use string comparison (gt ge lt le eq ne) as we don't use the dates as numbers (we don't add numbers to them etc.) but as strings (you can e.g. extract the year by substr $dt, 0, 4). Also, string comparison still works if you use a separator, e.g. 2018/09/25.

Upvotes: 4

Related Questions