arunmep has asked for the wisdom of the Perl Monks concerning the following question:

hi everybody I have two time Strings in 24:60:60 format i want to find the difference between them. Is any function in perl can do that. thank you

Replies are listed 'Best First'.
Re: how to get the time difference
by gellyfish (Monsignor) on Jul 26, 2006 at 09:16 UTC

    I'd suggest DateTime::Duration:

    use DateTime::Duration; + my $time1 = '11:30:25'; my $time2 = '12:45:40'; + my ( $h1,$m1,$s1 ) = split /:/, $time1; my ( $h2,$m2,$s2 ) = split /:/, $time2; + my $d1 = DateTime::Duration->new(hours => $h1, minutes => $m1, seconds + => $s1); my $d2 = DateTime::Duration->new(hours => $h2, minutes => $m2, seconds + => $s2); + my $diff = $d2 - $d1; + print +join ':',$diff->in_units('hours','minutes','seconds');

    /J\

Re: how to get the time difference
by davorg (Chancellor) on Jul 26, 2006 at 09:36 UTC

    Whilst using modules has already suggested and is a good solution to the problem, it's also possible to do this without modules. You just need to convert your time strings to seconds.

    my ($h, $m, $s) = split /:/, $your_time_goes_here; my $secs = $s + ($m * 60) + ($h * 60 * 60);

    You can then get the number of seconds between two times by subtracting.

    Of course, this gets more complicated if your timestamps span midnight or if you need to take into account daylight savings time or leap seconds. In those cases, you should definitely use something like DateTime::Duration.

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: how to get the time difference
by Crian (Curate) on Jul 26, 2006 at 09:06 UTC
Re: how to get the time difference
by jeanluca (Deacon) on Jul 26, 2006 at 13:39 UTC
    just an other example:
    #! /usr/bin/perl -l use strict; use warnings ; use Time::Local qw(timegm_nocheck); my $time1 = '12:44:01'; my $time2 = '12:45:01'; print "diff is ".(timegm_nocheck(split/:/,$time2) - timegm_nocheck(spl +it/:/,$time1)) ;

    LuCa