Oh the shame: my date objects weren't actually differing by more than one day because I'm an idiot and assumed that my inputs were what I thought they were! Thanks commenters for forcing me to go back and look at exactly what was in the objects. I leave this here as a memorial, or it can be reaped.

This is a bug in an application I'm working on.

The code creates two DateTime objects and subtracts one from the other to get a DateTime::Duration object.

However the DateTime::Duration object can't return a difference in number of days, which is what I need.

This is actually expected behaviour:


my $dur = DateTime::Duration->new( years => 1, months => 15 ); $dur->in_units('years'); # 2 $dur->in_units('months'); # 27 $dur->in_units( 'years', 'months' ); # (2, 3) $dur->in_units( 'weeks', 'days' ); # (0, 0) !
The last example demonstrates that there will not be any conversion between units which don't have a fixed conversion rate.

I guess my question is, how do I get the difference in days between two DateTime objects?

Updated: The current code just does

my $diff = $dt1 - $dt2;
Where both DateTime objects are specific fixed dates, like one is January 1, 2021 at 10 AM and the other is today at 11 AM. Surely there's a 'fixed conversion rate' in days between those? Note: They were essentially the same day!

I can understand that if I create a duration object with years => 1, months => 15 that's not something where we can be sure of the number of days, but that's not what's happening in my code.


In reply to I can't subtract one DateTime object from another to get a DateTime::Duration in days by Cody Fendant

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.