3.1. Finding Today's DateProblemYou need to find the year, month, and day values for today's date. Solution
Use ($DAY, $MONTH, $YEAR) = (localtime)[3,4,5];
Or, use Time::localtime, which overrides use Time::localtime; $tm = localtime; ($DAY, $MONTH, $YEAR) = ($tm->mday, $tm->mon, $tm->year); Discussion
Here's how you'd print the current date as "YYYY-MM-DD," using the non-overridden
($day, $month, $year) = (localtime)[3,4,5];
printf("The current date is %04d %02d %02d\n", $year+1900, $month+1, $day);
To extract the fields we want from the list returned by ($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 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 introducing temporary variables is: printf("The current date is %04d-%02d-%02d\n", sub {($_[5]+1900, $_[4]+1, $_[3])}->(localtime));
There is also use POSIX qw(strftime); print strftime "%Y-%m-%d\n", localtime;
The See Also
The |
|