我正在寻找一种在Perl中生成以下内容的不太长的方法:
获取当前时间(月,日和年)的代码的一部分.例如,如果我们在2013年5月27日,那么输出应该是20130527
我现在认为,如果我们使用"本地时间",就像
$date_str = localtime;
Run Code Online (Sandbox Code Playgroud)
输出格式为:Wed Jul 18 07:24:05 2001还有其他特殊变量可用吗?
您可以使用strftime
标准POSIX模块:
use POSIX 'strftime';
say strftime "%Y%m%d", localtime;
Run Code Online (Sandbox Code Playgroud)
输出:
20130526
Run Code Online (Sandbox Code Playgroud)
在Perl中,存储的时间是自The Epoch以来的秒数.时代通常是1970年1月1日.
这使得时间适合于排序和计算未来的日子.如果您需要知道从现在开始30天的日期,您可以添加2,592,000(30天内的秒数).
Perl有一个标准函数time
,它返回自The Epoch以来的秒数.然后,您可以使用localtime
或gmtime
将其转换为时间元素数组(日,年,小时等).
出于一些奇怪的原因,Perl从来没有一个内部函数来获取时间元素数组并将其转换回自The Epoch以来的秒数.但是,Perl总是有一个标准模块,它使用函数timelocal
和timegm
.在5.0之前的Perl日,你会的require "timelocal.pl";
.在Perl 5.0中,你现在use Time::Local;
.
转换的时间,因为背部和时间元件的阵列和所述秒之间来回的历元可以是一个有点痛与localtime
,gmtime
,timelocal
,和timegm
功能,并且在Perl 5.10,两个新的模块Time::Piece
和Time::Seconds
加入.这两个模块允许您使用的格式化时间strptime
和strftime
内置功能Time::Piece
.
如果你有Perl 5.10.0或更高版本,你可以轻松实现:
use Time::Piece;
my $time = localtime; #$time is a Time::Piece object
# $time_string is in YYYYMMDD format
my $time_string = sprintf "%04d%02d%02d%", $time->year, $time->month, $time->day;
# Another way to do the above using the strftime function:
my $time_string = $time->strftime("%Y%m%d");
Run Code Online (Sandbox Code Playgroud)
但是,您的程序应使用自The Epoch以来的秒数作为程序内部时间.您应该以这种格式存储时间.您应该以这种格式计算时间,并且您应该以这种格式为所有函数传递时间.
这是因为其他Perl模块需要这种格式的时间,更重要的是,其他将要查看和维护代码的Perl开发人员需要这种格式的时间.
#Converting the time from YYYYMMDD to seconds since the epoch
my $time = Time::Piece->strptime($YYYYDDMM_time, '%Y%m%d');
my $time_since_epoch = $time->epoch;
#Converting time since the epoch to YYYYMMDD
my $time = localtime($time_since_epoch);
my $YYYYMMDD_time = $time->strftime('%Y%m%d');
Run Code Online (Sandbox Code Playgroud)