Perl 格式的今天日期,格式为 MM/DD/YYYY 格式



我正在开发一个Perl程序,并坚持(我认为是)一个微不足道的问题。我只需要构建一个格式为"06/13/2012"的字符串(始终为 10 个字符,因此小于 10 的数字为 0)。

这是我到目前为止所拥有的:

use Time::localtime;
$tm=localtime;
my ($day,$month,$year)=($tm->mday,$tm->month,$tm->year);

您可以快速完成,只需使用一个 POSIX 函数。如果您有一堆带有日期的任务,请参阅模块日期时间。

use POSIX qw(strftime);
my $date = strftime "%m/%d/%Y", localtime;
print $date;

你可以使用 Time::Piece ,它不需要安装,因为它是一个核心模块,并且从版本 10 开始与 Perl 5 一起分发。

use Time::Piece;
my $date = localtime->strftime('%m/%d/%Y');
print $date;

输出

06/13/2012


更新

您可能更喜欢使用 dmy 方法,该方法采用单个参数,该参数是要在结果字段之间使用的分隔符,并且避免必须指定完整的日期/时间格式

my $date = localtime->dmy('/');

这会产生与我的原始解决方案相同的结果

use DateTime qw();
DateTime->now->strftime('%m/%d/%Y')   

表达式返回06/13/2012

如果你喜欢用艰难的方式做事:

my (undef,undef,undef,$mday,$mon,$year) = localtime;
$year = $year+1900;
$mon += 1;
if (length($mon)  == 1) {$mon = "0$mon";}
if (length($mday) == 1) {$mday = "0$mday";}
my $today = "$mon/$mday/$year";
use Time::Piece;
...
my $t = localtime;
print $t->mdy("/");# 02/29/2000

用于Unix系统的Perl代码:

# Capture date from shell
my $current_date = `date +"%m/%d/%Y"`;
# Remove newline character
$current_date = substr($current_date,0,-1);
print $current_date, "n";

使用"sprintf"可以轻松使用"sprintf"格式化数字,这是perl中的内置函数(文档:perldoc perlfunc)

use strict;
use warnings;
use Date::Calc qw();
my ($y, $m, $d) = Date::Calc::Today();
my $ddmmyyyy = sprintf '%02d.%02d.%d', $d, $m, $y;
print $ddmmyyyy . "n";

这为您提供:

2014.05.14

最新更新