Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: How do I find the difference in days between two dates, in a cool perl way?

by autarch (Hermit)
on May 10, 2004 at 19:39 UTC ( [id://352190]=note: print w/replies, xml ) Need Help??


in reply to How do I find the difference in days between two dates, in a cool perl way?

Using DateTime (assuming $dt1 and $dt2 are DateTime objects):
my $duration = $dt1->delta_days($dt2); print $duration->days;

Replies are listed 'Best First'.
Re: Answer: How do I find the difference in days between two dates, in a cool perl way?
by Anonymous Monk on Jul 12, 2016 at 14:31 UTC
    I believe this is incorrect. print $duration->days; Should be print $duration->delta_days; if your delta is greater than or equal to a calendar week.

      Anonymous Monk is correct.

      #!/usr/bin/env perl use strict; use warnings; use Test::More tests => 4; use DateTime; my $dt1 = DateTime->new ( year => 2015, month => 6, day => 1 ); my $dt2 = DateTime->new ( year => 2015, month => 6, day => 30 ); my $duration = $dt1->delta_days ($dt2); is $duration->days, 29, 'Without delta, more than a week'; is $duration->delta_days, 29, 'With delta, more than a week'; $dt2 = DateTime->new ( year => 2015, month => 6, day => 3 ); $duration = $dt1->delta_days ($dt2); is $duration->days, 2, 'Without delta, less than a week'; is $duration->delta_days, 2, 'With delta, less than a week';

      Test 1 fails for me (with DateTime 1.20) but the others all pass. This fits with the description of the days() method on a duration which says:

      These methods return numbers indicating how many of the given unit the object represents, after having done a conversion to any larger units. For example, days are first converted to weeks, and then the remainder is returned.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://352190]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2024-03-28 13:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found