Sch*_*ern 48
因为Perl内置的日期处理接口有点笨拙,你最终传递了六个变量,更好的方法是使用DateTime或Time :: Piece.DateTime是全唱,全舞蹈的Perl日期对象,你可能最终想要使用它,但Time :: Piece更简单,完全适合这项任务,具有5.10的优势,技术是两者基本相同.
这是使用Time :: Piece和strptime的简单,灵活的方式.
#!/usr/bin/perl
use 5.10.0;
use strict;
use warnings;
use Time::Piece;
# Read the date from the command line.
my $date = shift;
# Parse the date using strptime(), which uses strftime() formats.
my $time = Time::Piece->strptime($date, "%Y%m%d %H:%M");
# Here it is, parsed but still in GMT.
say $time->datetime;
# Create a localtime object for the same timestamp.
$time = localtime($time->epoch);
# And here it is localized.
say $time->datetime;
Run Code Online (Sandbox Code Playgroud)
对比之下,这是手动方式.
由于格式是固定的,正则表达式会很好,但如果格式改变,你将不得不调整正则表达式.
my($year, $mon, $day, $hour, $min) =
$date =~ /^(\d{4}) (\d{2}) (\d{2})\ (\d{2}):(\d{2})$/x;
Run Code Online (Sandbox Code Playgroud)
然后将其转换为Unix纪元时间(自1970年1月1日起的秒数)
use Time::Local;
# Note that all the internal Perl date handling functions take month
# from 0 and the year starting at 1900. Blame C (or blame Larry for
# parroting C).
my $time = timegm(0, $min, $hour, $day, $mon - 1, $year - 1900);
Run Code Online (Sandbox Code Playgroud)
然后回到当地时间.
(undef, $min, $hour, $day, $mon, $year) = localtime($time);
my $local_date = sprintf "%d%02d%02d %02d:%02d\n",
$year + 1900, $mon + 1, $day, $hour, $min;
Run Code Online (Sandbox Code Playgroud)
Vin*_*vic 21
这是一个使用DateTime及其strptime格式模块的示例.
use DateTime;
use DateTime::Format::Strptime;
my $val = "20090103 12:00";
my $format = new DateTime::Format::Strptime(
pattern => '%Y%m%d %H:%M',
time_zone => 'GMT',
);
my $date = $format->parse_datetime($val);
print $date->strftime("%Y%m%d %H:%M %Z")."\n";
$date->set_time_zone("America/New_York"); # or "local"
print $date->strftime("%Y%m%d %H:%M %Z")."\n";
$ perl dates.pl
20090103 12:00 UTC
20090103 07:00 EST
Run Code Online (Sandbox Code Playgroud)
use DateTime;
my @time = (localtime);
my $date = DateTime->new(year => $time[5]+1900, month => $time[4]+1,
day => $time[3], hour => $time[2], minute => $time[1],
second => $time[0], time_zone => "America/New_York");
print $date->strftime("%F %r %Z")."\n";
$date->set_time_zone("Europe/Prague");
print $date->strftime("%F %r %Z")."\n";
Run Code Online (Sandbox Code Playgroud)
这就是我要做的......
#!/usr/bin/perl
use Date::Parse;
use POSIX;
$orig = "20090103 12:00";
print strftime("%Y%m%d %R", localtime(str2time($orig, 'GMT')));
Run Code Online (Sandbox Code Playgroud)
您也可以使用Time::ParseDate而parsedate()不是Date::Parse和str2time().请注意事实上的标准atm.似乎是DateTime(但您可能不想仅使用OO语法来转换时间戳).
| 归档时间: |
|
| 查看次数: |
57600 次 |
| 最近记录: |