perl - How to make DateTime::Duration output only in days? -
this code finds difference between today , fixed date.
#!/usr/bin/perl use strict; use warnings; use data::dumper; use datetime (); use datetime::duration (); use datetime::format::strptime (); $date = "23/05-2022"; $parser = datetime::format::strptime->new( pattern => '%d/%m-%y', time_zone => 'local', ); $date = $parser->parse_datetime($date); $today = datetime->today(time_zone=>'local'); $d = datetime::duration->new($today - $date); print dumper $d->delta_days;
the problem is outputs -22 days.
if print dumper $d;
can see -130 months well.
$var1 = bless( { 'seconds' => 0, 'minutes' => 0, 'end_of_month' => 'preserve', 'nanoseconds' => 0, 'days' => -22, 'months' => -130 }, 'datetime::duration' );
how output result in days?
doing
print dumper $d->delta_days + $d->delta_months*30;
doesn't seam elegant solution.
at first need correct subtraction. there exists delta_md
, delta_days
, delta_ms
, subtract_datetime_absolute
. depending on unit later want, need pick right subtraction. problem not every unit convertible later without time_zone information. thats reason why need pick correct delta method.
for example day can have 23 hours or 24 or 25 hours, depending on time zone. because of that, need specify how subtraction should work. because want days later, subtraction need focus on days, rather focus on hours. don't use overload feature, because best fit.
that means need delta_days
subtraction.
my $dur = $date->delta_days($today);
now $dur datetime::duration
object. need knew tries best fit days, weeks, years, months if possible. means days split in weeks , days. because conversion constant.
if don't want "best fit" need call in_units
method , convert days.
my $days = $dur->in_units('days');
but said before in_units
can conversion possible. call in_units('hours')
not work on object , return 0 because cant convert days hours. if want hours example, need delta_ms
, , on object can call in_units('hours')
the complete example:
#!/usr/bin/env perl use 5.010; use strict; use warnings; use datetime; use datetime::format::strptime; $date = "23/05-2022"; $parser = datetime::format::strptime->new( pattern => '%d/%m-%y', time_zone => 'local', ); $date = $parser->parse_datetime($date); $today = datetime->new( day => 1, month => 7, year => 2011, time_zone => 'local' ); $dur = $date->delta_days($today); "weeks: ", $dur->weeks; "days: ", $dur->days; "absolute days: ", $dur->in_units('days'); "absolute hours: ", $date->delta_ms($today)->in_units('hours');
the output of program is:
weeks: 568 days: 3 absolute days: 3979 absolute hours: 95496
and info:
1) don't need load datetime::duration
loaded datetime
.
2) dont need (). these modules oop , don't export/import anything.
Comments
Post a Comment