tags:

views:

121

answers:

5

What's the most efficient way to get the current date in ISO format (e.g. "2010-10-06") using Perl?

+7  A: 

There are plenty of modules in the Date:: namespace, many of which can help you do what you need. Or, you can just roll your own:

my ($day, $mon, $year) = (localtime)[3..5];
printf "%04d-%02d-%02d\n", 1900+$year, 1+$mon, $day;

Resources

zigdon
Don't forget `DateTime`!
CanSpice
+9  A: 

Most efficient for you or the computer?

For you:

use POSIX qw/strftime/;

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

For the Computer:

my @t = localtime;
$t[5] += 1900;
$t[4]++;

printf "%04d-%02d-%02d", @t[5,4,3];
Chas. Owens
+3  A: 

You can use the Time::Piece module (bundled with Perl 5.10 and up, or you can download from CPAN), as follows:

use strict;
use warnings;
use Time::Piece;

my $today = localtime->ymd();        # Local time zone
my $todayUtc = gmtime->ymd();        # UTC
mscha
+3  A: 

Or you can use the DateTime module which seems to be the de facto standard date handling module these days. Need to install it from CPAN.

use DateTime;
my $now = DateTime->now->ymd;
Tim Jenness
standardizing on DateTime certainly makes things simpler for this programmer, and consistently using one fairly comprehensive module for everything seems a good idea in an area with many gotchas and inconsistencies such as date and time calculations
plusplus
+1  A: 

This doesn't create any temporary variables:

printf "%d-%02d-%02d", map { $$_[5]+1900, $$_[4]+1, $$_[3] } [localtime];
eugene y