How can I get the difference of two timestamps using Perl?

后端 未结 3 1931
情深已故
情深已故 2021-01-29 06:15

Here i based one problem.. i have two timestamps with same format like (Tue Dec 14 18:23:19 2010 & Tue Dec 14 17:23:19 2010). how can i get the difference of two timestamps

3条回答
  •  时光说笑
    2021-01-29 07:09

    You can take advantage of DateTime and its subtract_datetime() method, which returns a DateTime::Duration object.

    use Date::Parse;
    use DateTime;
    
    my $t1 = 'Tue Dec 14 17:23:19 2010';
    my $t2 = 'Tue Dec 14 18:23:19 2010';
    
    my $t1DateTime = DateTime->from_epoch( epoch => str2time( $t1 ) );
    my $t2DateTime = DateTime->from_epoch( epoch => str2time( $t2 ) );
    
    my $diff = $t2DateTime->subtract_datetime( $t1DateTime );
    
    print "Diff in hours: " . $diff->in_units('hours') . "\n";
    print "Diff in months: " . $diff->in_units('months') . "\n";
    

提交回复
热议问题