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 handles dates.
Time::Local
The following program uses the Time::Local module to determine my age in seconds:
#!/usr/bin/perl 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 = 751538646
Date::Calc
The Date::Calc module is a very powerful module that allows many different types of date calculations. The follow example calculates how old I am in days:
#!/usr/bin/perl 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 8698 days old
Date::Manip
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
Reviewed: ST
Revision: 1.1