如何使用Perl获得两个时间戳的差异?

jen*_*eny -1 perl

这里我基于一个问题..我有两个相同格式的时间戳(2010年12月14日18:23:19和2010年12月14日星期二17:23:19).我怎样才能在几小时内得到两个时间戳的差异.请帮我

Jiř*_*car 9

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";
Run Code Online (Sandbox Code Playgroud)


Dav*_*oss 5

我使用DateTime系列类来处理几乎所有的日期/时间处理.

#!/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;
Run Code Online (Sandbox Code Playgroud)

  • 但它的持续时间对于粗心大意有一些问题.如果两个时间戳有不同的天数,则代码不起作用. (3认同)