Linto
Linto

Reputation: 1282

How to get the date difference in seconds ,in perl

I have two dates , (they are datetime objects).

How can i get the difference between these two dates, in seconds ?

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',
  );

It should return the time difference as 75 secs

Upvotes: 3

Views: 2685

Answers (3)

Fernando Cano Duque
Fernando Cano Duque

Reputation: 11

Here you have a good solution using Time::Piece.

my $format = '%b %d %H:%M:%S %Y';

my $date2 = "$mes $dia $h:$m:$s $ano"; #'Aug 30 10:53:38 2013'
my $date1 = strftime($format, localtime(time())); #'Aug 30 10:53:38 2013'

my $diff = Time::Piece->strptime($date1, $format) - Time::Piece->strptime($date2, $format);

print "\n $date1 --> $date2 = $diff seconds.";

Adapt the format to your needs.

Upvotes: 0

Oesor
Oesor

Reputation: 6642

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

Outputs:

75

One minute is not always 60 seconds, so you can't convert a duration of 1 minute 15 seconds to 75 seconds.

Upvotes: 1

ikegami
ikegami

Reputation: 386696

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

Upvotes: 7

Related Questions