如何在Perl中以格式获取系统时钟?

时间:2014-09-12 08:33:31

标签: perl datetime

我想获得系统时钟(时间和日期)并在Perl中以人类可读的格式显示它。 格式如2014-09-12 15:13:56

#!/usr/local/bin/perl
my %months = qw(Jan Feb Mar Apr May  Jun  Jul
Aug  Sep  Oct  Nov Dec);
@weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear,   
$daylightSavings) = localtime();
$year = 1900 + $yearOffset;
$now = "$year-$months-$dayOfMonth $hour:$minute:$second";
print $now;

运行程序时,您应该看到更加可读的日期和时间,如下所示:

2014--12 16:57:15

如何将月份转换为数字?

3 个答案:

答案 0 :(得分:6)

使用Time::Piece(自perl v5.9.5后的核心模块)

use Time::Piece;
my $dt = localtime;
print $dt->ymd, " ", $dt->hms, "\n";

使用DateTime

use DateTime;
my $dt = DateTime->now();
print $dt->ymd, " ", $dt->hms, "\n";

答案 1 :(得分:4)

使用Perl模块更容易(POSIX不需要安装):

use POSIX qw/strftime/;
my $now_string = strftime "%Y-%m-%d %H:%M:%S", localtime;
print $now_string, "\n"; #<-- prints: 2014-09-12 11:09:45 (with my local time)

关于你的代码,有一个拼写错误:

$now = "$year-$months-$dayOfMonth $hour:$minute:$second";

应该是:

$now = "$year-$month-$dayOfMonth $hour:$minute:$second";

请务必在脚本的顶部写上use strict;use warnings;。它可以防止你出现这样的错误。

答案 2 :(得分:0)

我喜欢将这些日期和时间任务放入函数中以供重用。 这是我的方法:

use strict;
use warnings;

my $time_stamp = getTodaysDateTime();
print "Program Started: $time_stamp \n";

# do some processing 

$time_stamp = getTodaysDateTime();
print "Program Ended: $time_stamp \n";


# return date in specific format 
# ex: 2014-09-12 14:11:43
sub getTodaysDateTime {
    my ($sec,$min,$hour,$mday,$mon,$year,
        $wday,$yday,$isdst) = localtime(time);
    $year += 1900;
    $mon += 1;
    return sprintf("%d-%02d-%02d %02d:%02d:%02d",
        $year,$mon,$mday,$hour,$min,$sec);
}