in reply to calculate date difference

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 ));

Replies are listed 'Best First'.
Re^2: calculate date difference
by hujunsimon (Sexton) on Jul 07, 2010 at 11:04 UTC

    Thanks Ikegami, i have modified my code according to your suggestions. however now i got an error message when i run the code:"use of uninitialized value in negation <-> at c:/perl/site/lib/DateTime.pm line 1693."

    the code i modified as below:

    #declare packages used use DateTime qw( ); use DateTime::Format::Strptime qw( ); my $format = DateTime::Format::Strptime->new( pattern => '%Y-%m-%d %H:%M:%S', time_zone => 'local', ); while(<TEMP>) { my @line=split(";"); my @start_time1=($line[3]=~/(\d+)-(\d+)-(\d+)\s(\d+):(\d+):(\d+ +)/); my $start_time = $format->parse_datetime($line[3]);; + #parsing start time my $stop_time = $format->parse_datetime($line[4]); + #parsing stop time $_->set_time_zone('local') for $start_time, $stop_time; print "$start_time, $stop_time\n"; my $min_start = DateTime->new( year => 2007, month => 5, day => + 1,hour=>0, minute=>0,second=>0, time_zone => 'local' ); my $max_stop = DateTime->new( year => 2008, month => 4, day => + 30, hour=>23, minute=>59,second=>59, time_zone => 'local' ); + $start_time = $min_start if $start < $min_start; $stop_time = $max_stop if $stop >= $max_stop; my $dur = $start_time->delta_ms($stop_time); print"%d minutes and %d seconds\n, $dur->in_units(qw( minutes s +econds ))"; }

    many thanks for your help !

      hey Ikegami, no worries, i have resolved the problem. i made a mistake at define a variable. after i correct that mistake, all went well, bingo !

      thanks again and all the other monks who give the advices !