开发者

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

Here i base开发者_开发技巧d 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 in hours. please help me


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";


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;


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜