How do I find the number of days between two dates?

You want to know how many days until a certain date, or how long between two dates. Perl has many different modules to handle dates.


The following program uses the Time::Local module to determine the age (in seconds) of someone born on the 3rd of May in 1980.

You supply the timelocal() subroutine a date as a six-element array, and it returns the corresponding value in seconds since the system epoch.

Note that Time::Local expects that the value for the day of the month is a number in the range 1 to 31, while the value for the month itself is a number in the range 0 to 11, (since it is considered the number of months since January).

    use strict;
    use warnings;
    use Time::Local;

    my @today = localtime();
    my $time = timelocal(@today);

    my @birthday = (0, 54, 23, 3, 4, 1980);
    my $birthtime = timelocal(@birthday);

    print "My age in seconds = " . ($time - $birthtime) . "\n";

    exit 0;

The output of this program is something like:

    My age in seconds = 843513440


The Date::Calc module provides lots of great date and time functionality. The following example uses the Delta_Days() method to calculate how old the same person is in days (in other words, it calculates the days between two dates):

    use strict;
    use warnings;
    use Date::Calc qw(Delta_Days);

    my @today = (localtime)[5,4,3];
    $today[0] += 1900;

    my @birthday = (1980, 4, 3);

    my $days = Delta_Days(@birthday, @today);

    print "I am $days days old\n";

    exit 0;

The output of this example is something like:

    I am 9793 days old


See also

    perldoc Time::Local
    perldoc Date::Calc
    perldoc Date::Manip
    perldoc -q "How can I compare two dates and find the difference?"
    perldoc DateTime