开发者

How do I get the current date in ISO format using Perl?

开发者 https://www.devze.com 2023-01-19 03:38 出处:网络
What\'s the most efficient way to get the current date in ISO format (e.g. \"2010-10-06\") using Perl?开发者_开发技巧Most efficient for you or the computer?

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


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];


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;


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

  • Date:: namespace on The CPAN: http://search.cpan.org/search?query=Date%3A%3A&mode=module


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


This doesn't create any temporary variables:

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

精彩评论

暂无评论...
验证码 换一张
取 消