1

Novice here. Sorry and Thanks in advance. I have a future date

(ie:2013-06-09 / $fields[12])

I need to subtract today

(ie:2013-03-08)

to get the number of days remaining.

Krishnachandra Sharma
  • 1,332
  • 2
  • 20
  • 42
t a
  • 191
  • 1
  • 3
  • 14
  • 1
    Hmm... well, have you already tried searching for similar questions here on stackoverflow? :) (maybe something like this question: http://stackoverflow.com/questions/821423/how-can-i-calculate-the-number-of-days-between-two-dates-in-perl?rq=1) – summea Mar 08 '13 at 20:42
  • 1
    Yes I searched and found nothing similar. Your link would've helped. Thanks – t a Mar 08 '13 at 21:29

2 Answers2

5

I'd use DateTime. If you start with the date as a string, you could use DateTime::Format::Strptime to parse it.

use DateTime                   qw( );
use DateTime::Format::Strptime qw( );

my $format = DateTime::Format::Strptime->new(
    pattern   => '%Y-%m-%d',
    time_zone => 'local',
    on_error  => 'croak',
);

my $ref  = DateTime->today( time_zone => 'local' );
my $dt   = $format->parse_datetime('2013-06-09');
my $days = $ref->delta_days($dt)->in_units('days');

print(
   $dt < $ref ? "$days days ago\n" :
   $dt > $ref ? "$days days from now\n" :
   "today\n");
ikegami
  • 367,544
  • 15
  • 269
  • 518
1

use the DateTime module:

use DateTime;

my $d1 = DateTime->new(
      year       => 2013,
      month      => 9,
      day        => 6
);

my $d2 = DateTime->now;
my $diff = $d2->delta_days($d1);

print $diff->delta_days, "\n";  # 182 (from 8/3/2013)
Miguel Prz
  • 13,718
  • 29
  • 42
  • If you don't specify a time zone, it might give an answer that's wrong for where you are. It's not the same date everywhere in the world. – ikegami Mar 08 '13 at 21:19
  • 1
    `$dur->delta_days` is documented as being primarily for internal use. `->in_units('days')` is the preferred interface. – ikegami Mar 08 '13 at 21:20
  • $dur->delta_days is a math method, and I didn't see your advice in the documentation – Miguel Prz Mar 08 '13 at 21:24
  • 1
    I read the DateTime 0.78 documentation, and delta_days is a math method, according the author's definition – Miguel Prz Mar 08 '13 at 21:31
  • Then you read the wrong file of DateTime's documentation. You should have been looking at the docs for DateTime::Duration, since that's the method being discussed. It performs no math, and the entirety of its documentation can be summed up to "for internal use". (I had deleted this comment so Miguel could delete his, but his remains and is getting upvotes, so I'll address it again.) – ikegami Mar 09 '13 at 08:17