Looking at your question (not the code), it seems you're complicating the issue. Try the following approach:
  1. If the start date is before 2007-05-01,
    1. Set the start date to 2007-05-01.
  2. If the end date is before 2008-04-30,
    1. Set the end date to 2008-04-30.
  3. Calculate the difference.

I don't know why you're using both DateTime and Date::Calc. Here's a solution that uses the former.

my $format = DateTime::Format::Strptime->new( pattern => '%Y-%m-%d %H:%M:%S', time_zone => 'local', ); my $min_start = DateTime->new( year => 2007, month => 5, day => 1, tim +e_zone => 'local' ); my $max_stop = DateTime->new( year => 2008, month => 5, day => 1, tim +e_zone => 'local' );
my $start = $format->parse_datetime(...); my $stop = $format->parse_datetime(...); $start = $min_start if $start < $min_start; $stop = $max_stop if $stop >= $max_stop; my $dur = $start->delta_ms($stop); printf("%d minutes and %d seconds\n", $dur->in_units(qw( minutes secon +ds ));

In reply to Re: calculate date difference by ikegami
in thread calculate date difference by hujunsimon

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.