Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials

converting from date to epoch time

( categories: )

In most cases it's simpler to perform date calculations using epoch time (the numbers of seconds that have elapsed since a given date, in Unix is January 1, 1970).

If you have a date and want to convert it to epoch time, use the functions timelocal and timegm availabe in the module Time::Local.

These functions take as a parameter a date value (represented as a six-element array) and returns the epoch time.

#!/usr/bin/perl
use Time::Local
 
$time = timelocal($sec,$min,$hour,$mday,$mon,$year);
$time = timegm($sec,$min,$hour,$mday,$mon,$year);


adding (substracting) days to (from) a date

( categories: )

Use the function 'Add_Delta_Days' from 'Date::Calc' module.

The syntax of the function is:

Add_Delta_Days($year, $month, $day, $n_days)

where $n_days is the number of days you want to add (or substract) from the date specified with $year, $month and $n_days.

The function returns the calculated date as a list with 3 elements: year, month and day.

Example:

#-- add 60 days to November 4th, 1985
use Date::Calc qw(Add_Delta_Days);
($year, $month, $day) = Add_Delta_Days(1985,11,4,60);


determine the day of week

( categories: )

To determine the day of week of a given date, use the function 'Day_of_Week' from 'Date::Calc' module.

Day_of_Week expects 3 parameters: year, month and day (in that order); it returns '1' for Monday, '2' for Tuesday and so on until '7' for Sunday.

To obtain the name of the day, use the function 'Day_of_Week_to_Text' (also from 'Date::Calc' module).

Day_of_Week_to_Text receives as a parameter the day of week and returns a string with the corresponding name.

Example:


check if a year is a leap year

( categories: )

Use the 'leap_year' function from Date::Calc module. The function returns true if the argument is a leap year, false otherwise.

Example:

#!/usr/bin/perl
 
use Date::Calc qw(leap_year);
 
$year = 2000;
print "$year is a leap year\n" if ( leap_year($year) );


getting date and time information

( categories: )

Use 'localtime' or 'gmtime'. 'localtime' returns local time information and 'gmtime' returns time based on GMT time zone.

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);

Both functions expects as parameter the number of seconds since the epoch (00:00 January 1, 1970 for most systems, 00:00 January 1, 1904 for MacOS). That value is returned by the 'time' function.

The functions returns a 9-element list with the following structure:

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)

All the elements are numeric, the meaning of the elements are the following:


Syndicate content