Could you give a concrete example where this does not produce the expected output so we can reproduce the problem?

The DateTime documentation for the "subtraction" methods require careful reading. For example, from subtract_datetime (emphasis mine): "The returned duration may have deltas for months, days, minutes, seconds, and nanoseconds." (note there is no mention of weeks). And DateTime::Duration objects have conversion methods to convert between different measures of time, and conversions aren't always possible (see the module's documentation). Personally I try to stay away from this kind of math.

Also, what kind of difference are you looking for? A "logical" difference, like "2003-03-15 minus 2003-02-15 = 1 month" (that's the example from subtract_datetime, note how the answer is not given in days or weeks), or a "absolute" difference, that is, an exact difference between two points in time (in seconds/nanoseconds, which could then be converted to other measures)? Because if it's the latter, you need subtract_datetime_absolute:

my $dt1 = DateTime->from_epoch( epoch=>1403785930, time_zone=>'Europe/London' ); my $dt2 = DateTime->new( year=>2014, month=>6, day=>26, hour=>14, minute=>33, second=>03, nanosecond=>400e6, time_zone=>'Europe/Paris' ); my $diff_sec = $dt1->subtract_datetime_absolute($dt2) ->in_units('nanoseconds')/1e9; print "$diff_sec s\n"; __END__ -53.4 s

In reply to Re: Problem with DateTime subtract_datetime by Anonymous Monk
in thread Problem with DateTime subtract_datetime by phildeman

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.