I need to do the time difference as $date2-$date1
I'll assume you need the difference in seconds. If you need minutes or hours, divide by 60 or by 60/60.
I've used Date::Calc for a long time with fine results. There are several functions (as well as an OOP interface for the same functions) available, depending on what you need. You'll have to do a little parsing, but then you turn the string into the seconds since the epoch (doesn't matter which one) and just subtract one from the other.
use strict;
use warnings;
use Date::Calc qw(Mktime); # Turns a date string into seconds since ep
+och
my $dt_str2="31/12/2009 6:29:26 p.m.";
my $dt_str1="31/12/2009 6:14:25 p.m.";
my ($day, $mo, $yr, $hr, $min, $sec, $mer) =
$dt_str1 =~ m{(\d+)/(\d+)/(\d+) (\d+):(\d+):(\d+) ([ap])};
$hr += 12 if $mer eq 'p';
die "Problem with date string $_" if $hr > 23;
# Note element order for Date::Calc functions!
my $dt1 = Mktime($yr, $mo, $day, $hr, $min, $sec);
($day, $mo, $yr, $hr, $min, $sec, $mer) =
$dt_str2 =~ m{(\d+)/(\d+)/(\d+) (\d+):(\d+):(\d+) ([ap])};
$hr += 12 if $mer eq 'p';
die "Problem with date string $_" if $hr > 23;
my $dt2 = Mktime($yr, $mo, $day, $hr, $min, $sec);
print $dt2 - $dt1, "\n";
Or you could make it into a loop if you had a lot of these to parse at once (and it's cleaner looking too).
use strict;
use warnings;
use Date::Calc qw(Mktime); # Turns a date string into seconds since ep
+och
my $dt_str2="31/12/2009 6:29:26 p.m.";
my $dt_str1="31/12/2009 6:14:25 p.m.";
my @dates_to_compare;
for ($dt_str1, $dt_str2) {
my ($day, $mo, $yr, $hr, $min, $sec, $mer) =
m{(\d+)/(\d+)/(\d+) (\d+):(\d+):(\d+) ([ap])};
$hr += 12 if $mer eq 'p';
die "Problem with date string $_" if $hr > 23;
# Note element order for Date::Calc functi
+ons!
push @dates_to_compare, Mktime($yr, $mo, $day, $hr, $min, $sec);
}
# using pop clears out the array, which is helpful when looping
print pop(@dates_to_compare) - pop(@dates_to_compare), "\n";
I hope this helps
marmot |