Arav
Arav

Reputation: 5247

how to compare date string in Perl

I have two Perl string variables containing date values. I want to check whether str1 variable date value is 1 day before the str2 value. How can i check it? if it doesn't have 1 day before str2 then i need to print an error message.

 $str1="20120704"
 $str2="20120705

Upvotes: 2

Views: 3671

Answers (3)

Igor Chubin
Igor Chubin

Reputation: 64563

use Date::Parse;
$str1="20120704";
$str2="20120705";
@lt1 = localtime(str2time($str1)); 
@lt2 = localtime(str2time($str2));
if ($lt1[7] + 1 != $lt2[7]) {
  die "$str2 < $str1";
}

Upvotes: 4

LeoNerd
LeoNerd

Reputation: 8532

Since those date stamps are in ISO 8601 form, a simple string comparison is sufficient to compare them.

if( $str1 gt $str2 ) {
   # $str2 represents a later date than $str1
}

This is a specific feature of ISO 8601 form and doesn't necessarily apply to datestamps in other formats. Specifically note that it requires fields in the order year/month/day, and that month and day fields have 0-padding.

Upvotes: 1

Dave Cross
Dave Cross

Reputation: 69244

Use the standard Time::Piece module

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Time::Piece;

my $format = '%Y%m%d';

while (<DATA>) {
  chomp;
  my ($str1, $str2) = split;

  my $dt1 = Time::Piece->strptime($str1, $format);
  my $dt2 = Time::Piece->strptime($str2, $format);

  print "$str1 / $str2: ";
  if ($dt2->julian_day - $dt1->julian_day == 1) {
    say "ok";
  } else {
    say "not ok";
  }
}

__END__
20120704 20120705
20120630 20120701

Upvotes: 5

Related Questions