Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Perl, how do I compare dates in the form of YYYY-MM-DD?

Tags:

perl

I have an array with n strings in format of YYYY-MM-DD (Example, "2010-10-31").

How do I compare a date to the strings in this array?

For example, delete the strings more than 30 day ago?

like image 640
Bdfy Avatar asked Oct 12 '10 00:10

Bdfy


1 Answers

The great thing about YYYY-MM-DD-formatted dates is that you can compare them using simple string comparison. In Perl, that's the lt and gt operators.

In this case, it sounds like you're just looking to check whether the dates in the array are earlier or later than a given target date (which just happens to be "30 days ago"). For that case, the approach I would take would be to first determine what the date was 30 days ago and then compare that as a string against each date in the array. I would not introduce the overhead of converting all the YYYY-MM-DD strings into "proper" date objects, epoch times, etc. and back just for the sake of testing which represents the earlier date.

#!/usr/bin/env perl

use strict;
use warnings;

my $thirty_days = 30 * 24 * 60 * 60;
my ($old_day, $old_month, $old_year) = (localtime(time - $thirty_days))[3..5];
my $cutoff = sprintf('%04d-%02d-%02d', 
                     $old_year + 1900, $old_month + 1, $old_day);

my @dates = ('2010-10-12', '2010-09-12', '2010-08-12', '2010-09-13');
for my $date (@dates) {
  print "$date\n" if $date gt $cutoff;
} 
like image 191
Dave Sherohman Avatar answered Oct 07 '22 00:10

Dave Sherohman