How can I calculate the number of days between two dates in Perl?

前端 未结 7 2306
长发绾君心
长发绾君心 2020-12-05 19:05

I want to calculate (using the default Perl installation only) the number of days between two dates. The format of both the dates are like so 04-MAY-09. (DD-MMM-YY)

I

相关标签:
7条回答
  • 2020-12-05 19:48

    If you care about accuracy, keep in mind that not all days have 86400 seconds. Any solution based on that assumption will not be correct for some cases.

    Here's a snippet I keep around to calculate and display date/time differences a few different ways using the DateTime library. The last answer printed is the one you want, I think.

    #!/usr/bin/perl -w
    
    use strict;
    
    use DateTime;
    use DateTime::Format::Duration;
    
    # XXX: Create your two dates here
    my $d1 = DateTime->new(...);
    my $d2 = DateTime->new(...);
    
    my $dur = ($d1 > $d2 ? ($d1->subtract_datetime_absolute($d2)) : 
                           ($d2->subtract_datetime_absolute($d1)));
    
    my $f = DateTime::Format::Duration->new(pattern => 
      '%Y years, %m months, %e days, %H hours, %M minutes, %S seconds');
    
    print $f->format_duration($dur), "\n";
    
    $dur = $d1->delta_md($d2);
    
    my $dy = int($dur->delta_months / 12);
    my $dm = $dur->delta_months % 12;
    print "$dy years $dm months ", $dur->delta_days, " days\n";
    print $dur->delta_months, " months ", $dur->delta_days, " days\n";
    print $d1->delta_days($d2)->delta_days, " days\n";
    
    0 讨论(0)
提交回复
热议问题