JavaScript EditorFreeware JavaScript Editor     Perl Tutorials 

Main Page Previous Section Next Section

Recipe 3.1 Finding Today's Date

3.1.1 Problem

You need to find the year, month, and day values for today's date.

3.1.2 Solution

Use localtime, which returns values for the current date and time if given no arguments. You can either use localtime and extract the information you want from the list it returns:

($DAY, $MONTH, $YEAR) = (localtime)[3,4,5];

or use Time::localtime, which overrides localtime to return a Time::tm object:

use Time::localtime;
$tm = localtime;
($DAY, $MONTH, $YEAR) = ($tm->mday, $tm->mon, $tm->year);

3.1.3 Discussion

Here's how you'd print the current date as "YYYY MM DD", using the non-overridden localtime:

($day, $month, $year) = (localtime)[3,4,5];
printf("The current date is %04d %02d %02d\n", $year+1900, $month+1, $day);
The current date is 2003 03 06

To extract the fields we want from the list returned by localtime, we take a list slice. We could also have written it as:

($day, $month, $year) = (localtime)[3..5];

This is how we'd print the current date as "YYYY-MM-DD" (in approved ISO 8601 fashion), using Time::localtime:

use Time::localtime;
$tm = localtime;
printf("The current date is %04d-%02d-%02d\n", $tm->year+1900, 
    ($tm->mon)+1, $tm->mday);
The current date is 2003-03-06

The object interface might look out of place in a short program. However, when you do a lot of work with the distinct values, accessing them by name makes code much easier to understand.

A more obfuscated way that does not involve temporary variables is:

printf("The current date is %04d-%02d-%02d\n",
       sub {($_[5]+1900, $_[4]+1, $_[3])}->(localtime));

There is also strftime from the POSIX module discussed in Recipe 3.8:

use POSIX qw(strftime);
print strftime "%Y-%m-%d\n", localtime;

The gmtime function works just as localtime does, but gives the answer in UTC instead of your local time zone.

3.1.4 See Also

The localtime and gmtime functions in perlfunc(1) and Chapter 29 of Programming Perl; the documentation for the standard Time::localtime module

    Main Page Previous Section Next Section

    JavaScript EditorJavaScript Verifier     Perl Tutorials