Home > Perl > Modules and Packages > Manipulating Dates in Perl
Manipulating Dates in Perl
Written by Philip L Yuson   

Who is this for

This is for those who want to know more about using dates in Perl

What you need to know

Basic Perl programming

Introduction

One of the important things that you might need to know is using dates in Perl. Perl has a built-in function that gives you the current date and time. But what if you need to know what day a specific date is? Or if you want to convert 2002/06/20 to 2002 June 20?

Fortunately, there is a Perl module that does this and more.

Date::Calc Module

The Date::Calc module is a that contains several handy date functions. Like all modules, you need to install Date::Calc .

The Date::Calc module however, does not have a new method. This means that you have to eith import the functions you need from the module or call the functions by specifying the module.

So, to find out the number of days between two dates, you will need to import (or have the module export) the Delta_Days function.

use Date::Calc qw(Delta_Days);
print Delta_Days(2002, 06, 20, 2001, 06, 20);



If you run this script, the result will be

-365.



You can also do this:

use Date::Calc;
print Date::Calc::Delta_Days(2002, 06,20, 2001, 06, 20);



The result will be the same:

-365;



You can also convert a date to its text form:

use Date::Calc qw(Date_to_Text Date_to_Text_Long);
print “Date To Text: “, Date_to_Text(2002, 06, 20), “\n”;
print “Date To Text Long: “, Date_to_Text_Long(2002, 06, 20);



The result will be:

Date To Text:: Thu 20-Jun-2002
Date To Text Long: Thursday, June 20th 2002



Other things you can do with Date::Calc is to determine the day of the week.

Use Date::Calc qw(Day_of_Week_to_Text Day_of_Week);
print Day_of_Week_to_Text(Day_of_Week);



The result is:

Thursday



Perl localtime Function

Perl has the localtime funtion. This function returns an array with 9 elements that normally represents the time and date at the time localtime was called. When you make this call:

@ltime = localtime;



the result will be:

Element number

Description

$ltime[0]

Seconds

$ltime[1]

Minutes

$ltime[2]

Hour

$ltime[3]

Day

$ltime[4]

Month – with January as month 0

$ltime[5]

Year. This has to be added to 1900 to get the actual year

$ltime[6]

Weekday (Sunday is 0, Monday is 1, ...)

$ltime[7]

Day of the year with Jan 1 as day 1

$ltime[8]

1 if DST is in effect in the time zone. 0 if no DST



So to get the long text of the current date, you can write this:

use Date::Calc qw(Date_to_Text);
@ltime = localtime;
print Date_to_Text($ltime[5]+1900, $ltime[4]+1, $ltime[3]);



If the current date is June 20, 2002, the result is:

06/20/02

 
Copyright: © 2018 Philip Yuson