如何以秒为单位获取日期差异,以perl为单位

时间:2014-03-05 11:42:07

标签: perl

我有两个日期,(它们是日期时间对象)。

如何才能在几秒钟内得出这两个日期之间的差异?

my $givenDate1 =  DateTime->new(
      year       => 1982,
      month      => 10,
      day        => 25,
      hour       => 7,
      minute     => 19,
      second     => 35,

      time_zone  => 'UTC',
  );
my $givenDate2 =  DateTime->new(
      year       => 1982,
      month      => 10,
      day        => 25,
      hour       => 7,
      minute     => 20,
      second     => 50,

      time_zone  => 'UTC',
  );

它应该将时差记录为75秒

2 个答案:

答案 0 :(得分:5)

say $givenDate2->epoch - $givenDate1->epoch;

答案 1 :(得分:1)

my $givenDate1 =  DateTime->new(
      year       => 1982,
      month      => 10,
      day        => 25,
      hour       => 7,
      minute     => 19,
      second     => 35,

      time_zone  => 'UTC',
  );
my $givenDate2 =  DateTime->new(
      year       => 1982,
      month      => 10,
      day        => 25,
      hour       => 7,
      minute     => 20,
      second     => 50,

      time_zone  => 'UTC',
  );
say $givenDate1->subtract_datetime_absolute($givenDate2)->seconds

输出:

75

一分钟并不总是60秒,因此您无法将1分15秒的持续时间转换为75秒。