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

All i have a question about the best way to compare date strings. I have the following two dates.
my $date1 = "2006/01/03 03:59:59:671"; my $date2 = "2006/01/03 04:00:00:562";
Now would the best way to get how many seconds / milliseconds there are between them to do. First strip out the 2006 day month as they are the same ? or leave them and do
$date1 =~ s/://g; $date2 =~ s/://g; my $ordermilliseconds = $clsendtimestamp - $clrectimestamp; my $ordersecs = $ordermilliseconds / 1000;

Replies are listed 'Best First'.
Re: Best way to compare date strings
by davorg (Chancellor) on Jan 04, 2006 at 12:01 UTC

    Use the DateTime family of modules.

    #!/usr/bin/perl use strict; use warnings; use DateTime::Format::Strptime; my $fmt = DateTime::Format::Strptime->new(pattern => '%Y/%m/%d %H:%M:% +S:%3N'); my $date1 = $fmt->parse_datetime('2006/01/03 03:59:59:671'); my $date2 = $fmt->parse_datetime('2006/01/03 04:00:00:562'); my $diff = $date2 - $date1; print $diff->in_units('nanoseconds'), "\n";
    --
    <http://dave.org.uk>

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

      Strange when i install the mods and run i get.
      $ perl test.pl Can't call method "in_units" on an undefined value at test.pl line 22.
        I downloaed the modules again and installed them, still get strange errors
        $ perl test.pl Scalar found where operator expected at (eval 4) line 1, near "%+$nano +second" (Missing operator before $nanosecond?) syntax error at (eval 4) line 1, near "%+$nanosecond"
Re: Best way to compare date strings
by derby (Abbot) on Jan 04, 2006 at 15:04 UTC

    In the TMTOWTDI mode:

    #!/usr/local/bin/perl -d use strict; use warnings; use Time::Local; use Time::HiRes qw( tv_interval ); my $date1 = "2006/01/03 03:59:59:671"; my $date2 = "2006/01/03 04:00:00:562"; my $t1 = convert_time( $date1 ); my $t2 = convert_time( $date2 ); my $elapsed = tv_interval( $t1, $t2 ); print $elapsed, "\n"; sub convert_time { my $date = shift; my( $yr, $mo, $dy ) = split( /\//, substr( $date, 0, 10 ) ); my( $hr, $mn, $sc, $mi ) = split( /:/, substr( $date, 11 ) ); my $epoch = timelocal( $sc, $mn, $hr, $dy, $mo-1, $yr-1900 ); [ $epoch, $mi*1000 ]; }
    -derby
      That looks good
Re: Best way to compare date strings
by Anonymous Monk on Jan 04, 2006 at 12:49 UTC
    my @seconds = ();
    for my $date ( $date1, $date2 ) { my @fields = ( split( /:/, $date ); my $frac = pop @fields; my $sec = pop @fields; push @seconds, join( '.', ( $sec, $frac ) ); }