7

I am a novice in perl scripting. I have a requirement where in I need to find the difference of two dates in the minutes/seconds

$date1 =  Fri Aug 30 10:53:38 2013
$date2 =  Fri Aug 30 02:12:25 2013

can you tell me how do we achieve this, Parsing , calculation , modules req and all

Thanks Goutham

1

2 Answers 2

15

Time::Piece has been a standard part of Perl since 2007.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;
use Time::Piece;

my $date1 = 'Fri Aug 30 10:53:38 2013';
my $date2 = 'Fri Aug 30 02:12:25 2013';

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

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

say $diff;
1
  • Time::Piece->strptime is for dealing with UTC times. If dealing with local times, use Time::Piece::localtime->strptime instead.
    – ikegami
    Apr 26, 2020 at 9:31
1

Convert both dates to UNIX time

See http://metacpan.org/pod/Date::Parse

Then you can do a simple mathematical subtraction to find the number of seconds between the two.

Then it is simple maths all the way to get minutes, hours, etc.

1
  • Doing math will not get you the correct answer.
    – Ian Hyzy
    Dec 20, 2016 at 21:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.