Reputation: 45
I have two datetime strings as:
$bstr = 02/07/17 09:25:22
$betr = 02/07/17 10:55:48
my $bstrDateTime = DateTime->from_epoch( epoch => str2time( $bstr ) );
my $betrDateTime = DateTime->from_epoch( epoch => str2time( $betr ) );
my $diff = $betrDateTime->subtract_datetime( $bstrDateTime );
$diff_h = sprintf $diff->in_units('hours');
$diff_m = sprintf $diff->in_units('minutes');
$diff_s = sprintf $diff->in_units('seconds');
$difference = $diff_h.":".$diff_m.":".$diff_s;
print $difference;
But I am getting wrong minute difference.
Output was: 1:90:48
Where I have done wrong? Instead of 90, it should be 30.
Upvotes: 1
Views: 821
Reputation: 69244
It helps if you give us code that actually compiles, so we don't have to spend time fixing your missing semicolons and quotes.
Using str2time()
and creating a DateTime object from the epoch is a little wasteful. Better to use DateTime::Format::Strptime to directly parse your string to a DateTime object.
Using the hours()
, minutes()
and seconds()
methods on DateTime::Duration (instead of in_units()
) will give you the results to want.
use strict;
use warnings;
use DateTime::Format::Strptime;
my $date_parser = DateTime::Format::Strptime->new(
pattern => '%d/%m/%y %H:%M:%S',
);
my $bstr = '02/07/17 09:25:22';
my $betr = '02/07/17 10:55:48';
my $bstrDateTime = $date_parser->parse_datetime( $bstr );
my $betrDateTime = $date_parser->parse_datetime( $betr );
my $diff = $betrDateTime->subtract_datetime( $bstrDateTime );
print $diff->hours, ', ', $diff->minutes, ', ', $diff->seconds, "\n";
Upvotes: 1
Reputation: 608
You are currently using in_units but it is not doing what you expect. As it has different functionality as it calculates the difference between the given objects in the specified unit. Provided that they are conversion compatible. For more information on this refer - DateTime::Duration or StackOverflow.
Now the correct code which will give your desired output is below:
my $bstr = '02/07/17 09:25:22';
my $betr = '02/07/17 10:55:48';
my $bstrDateTime = DateTime->from_epoch(epoch => str2time($bstr));
my $betrDateTime = DateTime->from_epoch(epoch => str2time($betr));
my $diff = $betrDateTime->subtract_datetime( $bstrDateTime );
my $diff_h = $diff->hours;
my $diff_m = $diff->minutes;
my $diff_s = $diff->seconds;
my $difference = $diff_h.":".$diff_m.":".$diff_s;
print $difference;
Also you should have placed the timestamps inside quotes in your code posted and semicolon is also missing in the first couple of lines too. Do remember to run the code which you are pasting to avoid these kinds of errors.
Upvotes: 1