Hi monks,
i have question regarding to calculate the time difference between two dates. here is my problem:
i have a event based dataset, each event is with start and stop time. i want to calculate the duration of each event, which between time 2007-05-01 to 2008-04-30.
i used the Date::Calc qw module and try to calculate the duration, however if i use delta_ms, as you know, it only gives the absolute value of the two differnt dates. that doesn't really help. anyone knows how to compare the two dates, if the earlier date subtracts the later date, it will gives a negative number ???
also attached my code here for your reference:
#!/usr/bin/perl #declare packages used use DateTime qw( ); use DateTime::Format::Strptime qw( ); use Date::Calc qw(Delta_YMDHMS); use Date::Calc qw(Add_Delta_DHMS); my $format = DateTime::Format::Strptime->new( pattern => '%Y-%m-%d %H:%M:%S', ); 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 $initial_time=$format->parse_datetime("2007-5-1 00:00:00"); my $end_time=$format->parse_datetime("2008-4-30 23:59:59"); my $min_diff_1 = $start_time- $stop_time; print "$min_diff_1"; my $min_diff_2 = $start_time->delta_ms($initial_time)->in_units +('minutes'); my $min_diff_3 = $start_time->delta_ms($end_time)->in_units('mi +nutes'); my $min_diff_4 = $stop_time->delta_ms($initial_time)->in_units( +'minutes'); my $min_diff_5 = $stop_time->delta_ms($end_time)->in_units('min +utes'); my $min_diff_6 = $initial_time->delta_ms($stop_time)->in_units( +'minutes'); if ($min_diff_2>0 && $min_diff_3<0 && $min_diff_4<0 && $min_dif +f_5>0) { print OUTPUT "$line[0],$line[1],$line[2],$line[3],$line[4],$lin +e[5],$line[6],$line[7],$line[8],$line[9],$line[10],$line[11],$line[12 +],$line[13],$min_diff_6\n"; } elsif ($min_diff_2<0 && $min_diff_3>0 && $min_diff_4<0 && $min_ +diff_5>0) { print OUTPUT "$line[0],$line[1],$line[2],$line[3],$line[4],$lin +e[5],$line[6],$line[7],$line[8],$line[9],$line[10],$line[11],$line[12 +],$line[13],$min_diff_1\n"; print "$min_diff_1,$min_diff_2,$min_diff_3,$min_diff_4,$min_dif +f_5,$min_diff_6 \n"; } elsif ($min_diff_2<0 && $min_diff_3>0 && $min_diff_4<0 && $min_ +diff_5<0) { print OUTPUT "$line[0],$line[1],$line[2],$line[3],$line[4],$lin +e[5],$line[6],$line[7],$line[8],$line[9],$line[10],$line[11],$line[12 +],$line[13],$min_diff_3\n"; } }
In reply to calculate date difference by hujunsimon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |