0

I have two dates in the format year-month-day hour:minute:sec

For example : 2015-01-01 10:00:00 and 2015-01-10 11:00:00. I want to calculate number of days between these two days as 10.

I tried localtime function, but didn't work. I need a solution for this in perl. Please help.

Futuregeek
  • 1,900
  • 3
  • 26
  • 51
  • 1
    For example, the [Time::Piece](https://metacpan.org/pod/Time::Piece) with [Time::Seconds](https://metacpan.org/pod/Time::Seconds) could help a lot. – clt60 May 28 '15 at 19:40
  • 1
    Are you rounding everything up? I would expect the difference for those dates to be 9 days (plus a smidge), not 10 days. Similarly, I would expect the difference between `2015-01-01` and `2015-01-02` to be 1 day, not 2 days. – ThisSuitIsBlackNot May 28 '15 at 19:55
  • 1
    Similar: [How can I calculate the number of days between two dates in Perl?](http://stackoverflow.com/q/821423/176646) – ThisSuitIsBlackNot May 28 '15 at 20:04
  • 1
    what if the times were 10 and 10? 11 and 10? are these in some particular timezone? if so, what would be the expected effect on the result if daylight savings started or ended between the two times? – ysth May 28 '15 at 22:58
  • it was like hotel check in/out times : 10 to 10 calculated as one day and 10 to 10:30 will be calculated as two days – Futuregeek Jun 01 '15 at 07:14

2 Answers2

7

Time::Piece has been a standard module in Perl for awhile:

use strict;
use warnings;

use feature qw(say);
use Time::Piece;

my $date1 = '2015-01-01 10:00:00';
my $date2 = '2015-01-10 11:00:00';

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

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

# subtraction of two Time::Piece objects produces a Time::Seconds object 
say $diff->days;
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
1

Try this:

(
    Time::Piece->strptime('2015-01-01 10:00:00', '%Y-%m-%d %H:%M:%S')
  - Time::Piece->strptime('2015-01-10 11:00:00', '%Y-%m-%d %H:%M:%S')
)->days

Since v5.9.5 Time::Piece is part of the core Perl distribution

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331