Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate a DateTime difference in Perl?

Tags:

perl

use DateTime ;

my $date = "2010-08-02 09:10:08";

my $dt = DateTime->now( time_zone => 'local' )->set_time_zone('floating');
print $dt->subtract_datetime($date);

It's not working; what is the problem?

The error message is:

Can't call method "time_zone" without a package or object reference at
/opt/perl/perl5.12/lib/site_perl/5.12.0/x86_64-linux/DateTime.pm line 1338
like image 918
Tree Avatar asked Aug 02 '10 14:08

Tree


People also ask

How to calculate time difference in Perl?

$Diff."\n"; This is a simple way to find the time difference in seconds.

How do I compare two dates in Perl?

my $days = $dt1->delta_days($dt2)->delta_days; $cmp is -1, 0 or 1, depending on whether $dt1 is less than, equal to, or more than $dt2 . One of the many nice things about DateTime is it has full operator overloading -- e.g. you can compare two DateTime objects as if ($dt1 < $dt2) { ... }


2 Answers

You need to convert date strings into DateTime objects first, using a customized format or one of the many DateTime::Format::* libraries available. You're using a format commonly used in databases, so I've selected the MySQL formatter (and then defined a custom duration formatter for the end result, copied from the examples in DateTime::Format::Duration):

use DateTime;
use DateTime::Format::MySQL;
use DateTime::Format::Duration;

my $date = "2010-08-02 09:10:08";

my $dt1 = DateTime->now(time_zone => 'floating', formatter => 'DateTime::Format::MySQL');
my $dt2 = DateTime::Format::MySQL->parse_datetime($date);

my $duration = $dt1 - $dt2;
my $format = DateTime::Format::Duration->new(
    pattern => '%Y years, %m months, %e days, %H hours, %M minutes, %S seconds'
);
print $format->format_duration($duration);

# prints:
# 0 years, 00 months, 0 days, 00 hours, 421 minutes, 03 seconds
like image 184
Ether Avatar answered Sep 30 '22 14:09

Ether


$date must be a DateTime object, not a simple string. See DateTime. And, you can not simply print the return value of subtract_datetime because it returns a reference. You must use methods, such as hours, to extract useful info.

use strict;
use warnings;
use DateTime;

my $dt2 = DateTime->new(
                       year   => 2010,
                       month  => 8,
                       day    => 2,
                       hour   => 9,
                       minute => 10,
                       second => 8,
                       time_zone => 'local',
                     );

my $dt1 = DateTime->now( time_zone => 'local' )->set_time_zone('floating');

my $dur = $dt1->subtract_datetime($dt2);
print 'hours = ', $dur->hours(), "\n";

__END__

hours = 2
like image 42
toolic Avatar answered Sep 30 '22 15:09

toolic