S, Rajini (STSD) wrote:
> From: Gunnar Hjalmarsson [mailto:nore...@gunnar.cc] 
>> S, Rajini (STSD) wrote:
>>>
>>> I am new to Perl Programming and have a query in perl. 
>>>
>>> In perl is there any system defined functions to find out the 
>>> Differences in dates.
>>>
>>> Eg : 
>>>
>>> Date 1 -> 26-Jan-2009
>>> Date 2 -> 14-Jan-2009
>>>
>>> So the difference between two dates is 12 days. 
>>>
>>> Is there a way to achieve this with any system defined functions In 
>>> Perl ????
>>
>> It depends on what you mean by "system defined functions". As 
>> others have told you, there are many CPAN modules that deal 
>> with date and time related tasks. Your particular problem can 
>> be easily solved using only a module that is included in the 
>> standard Perl distribution.
>>
>>     use Date::Parse;
>>
>>     my $time1 = str2time '26-Jan-2009';
>>     my $time2 = str2time '14-Jan-2009';
>>
>>     print 'Difference: ',
>>       sprintf( '%.0f', ($time1-$time2)/86400 ), " days\n";
>>
>
> Thanks Gunnar for the suggestions. 
> 
> In which version of perl is Parse module available. 
> 
> We have perl version 5.8.0 and parse module is not available. 

(Please bottom-post your responses to this group. Thank you.)

As far as I know Gunnar is mistaken and Date::Parse is not a standard module in
any version of Perl. However Time::Local is, and you may be interested in the
solution below that uses it. If your dates aren't guaranteed to be well-formed
then you may want to do some checking on them before you call the epoch_days
function.

HTH,

Rob


use strict;
use warnings;

use Time::Local;

my $days1 = epoch_days('26-Jan-2009');
my $days2 = epoch_days('14-Jan-2009');

print "Difference: @{[$days1 - $days2]} days\n";

BEGIN {

  my %month_num = do {
    my $n = 1;
    map(($_, $n++), qw/jan feb mar apr may jun jul aug sep oct nov dec/);
  };

  sub epoch_days {

    my @dmy = split /-/, shift;
    $dmy[1] = $month_num{lc $dmy[1]} || 0;

    return timelocal(0, 0, 0, @dmy) / (24 * 60 * 60);
  }
}

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to