how to get year difference between two date in perl like below date
my $date1 = '2012-08-29T00:00:00.0000Z'
my $date2 = '2010-08-29T00:00:00.0000Z'
need help and advise on it .thanks
how to get year difference between two date in perl like below date
my $date1 = '2012-08-29T00:00:00.0000Z'
my $date2 = '2010-08-29T00:00:00.0000Z'
need help and advise on it .thanks
use DateTime::Format::RFC3339 qw( );
my $format = DateTime::Format::RFC3339->new();
my $dt1 = $format->parse_datetime('2010-08-29T00:00:00.0000Z');
my $dt2 = $format->parse_datetime('2012-08-29T00:00:00.0000Z');
my $dur = $dt2 - $dt1;
say sprintf "%d years", $dur->in_units('years');
Ref: DateTime, DateTime::Duration, DateTime::Format::RFC3339
A lightweight alternative to the correct solutions others will post:
my $date1 = '2012-08-29T00:00:00.0000Z';
my $date2 = '2010-08-29T00:00:00.0000Z';
my $years_diff = do { no warnings "numeric"; $date1 - $date2 };
Note that there are probably dozens of different ways to specify how you would want partial years to be rounded in this seemingly trivial question.
If you don't care about hours or leap years, you can truncate off the times and use Date::Simple.
my $days = Date::Simple->new(substr $date2, 0, 10) - Date::Simple->new(substr $date1, 0, 10);
my $years = int($days / 365);