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
$Diff."\n"; This is a simple way to find the time difference in seconds.
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) { ... }
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
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With