How to compare string date time in perl?

后端 未结 6 864
醉梦人生
醉梦人生 2021-01-13 10:37

I have this date time format in string \"11:56:41, 11/22/2011\".

Here\'s what I want:

Compare two date time strings like.

$date1 = \"11:56:41         


        
6条回答
  •  死守一世寂寞
    2021-01-13 11:09

    Convert the datetimes (in your case these are local datetimes because they have no time zones) into ISO8601 then you can do regular string comparison.

    To perform the conversion, you should extract the six components from your format

    HH:MM:SS, mm/DD/YYYY
    

    and reassemble them into ISO 8601:

    YYYY-MM-DDTHH:MM:SS
    

    Then a normal lexicographic comparison will work.

    See http://codepad.org/berle9um

    Repeated here:

    sub my_format_to_iso8601 {
        $_[0] =~ /(\d\d):(\d\d):(\d\d), (\d\d)\/(\d\d)\/(\d\d\d\d)/;
        return "$6-$4-$5T$1:$2:$3";
    }
    
    $date1 = "11:56:41, 11/22/2011";
    $date2 = "11:20:41, 11/20/2011";
    $d1 = my_format_to_iso8601($date1);
    $d2 = my_format_to_iso8601($date2);
    print "first is $d1\n";
    print "second is $d2\n";
    if ($d2 < $d1) {
        print "second is earlier\n";
    } else {
        print "first is earlier\n";
    }
    

    ADDENDUM

    • ikegami's Perl code is much better.
    • A date library would be your friend here; simply specify a format string and use the library's parse function to get your date object, which it should then be able to compare directly. (That said, it is always fun to point out that ISO8601 is, by design, sortable in string form.)

提交回复
热议问题