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

后端 未结 3 1932
情深已故
情深已故 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 06:45
    use Date::Parse;
    
    
    my $t1 = 'Tue Dec 14 17:23:19 2010';
    my $t2 = 'Tue Dec 14 18:23:19 2010';
    
    my $s1 = str2time( $t1 );
    my $s2 = str2time( $t2 );
    
    print $s2 - $s1, " seconds\n";
    
    0 讨论(0)
  • 2021-01-29 06:46

    I use the DateTime family of classes for pretty much all of my date/time handling.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use DateTime::Format::Strptime;
    
    my $dp = DateTime::Format::Strptime->new(
      pattern => '%a %b %d %H:%M:%S %Y'
    );
    
    # Create two DateTime objects
    my $t1 = $dp->parse_datetime('Tue Dec 14 17:23:19 2010');
    my $t2 = $dp->parse_datetime('Tue Dec 14 18:23:19 2010');
    
    # The difference is a DateTime::Duration object
    my $diff = $t2 - $t1;
    
    print $diff->hours;
    
    0 讨论(0)
  • 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";
    
    0 讨论(0)
提交回复
热议问题