使用此功能:如何在Perl中更改日期時間值的時區?
perl -e 'use Time::Local; print timelocal("00","00","00","01","01","2000"),"\n";'
它會返回一個epochtime - 但只有在格林尼治標準時間 - 如果我想要的結果在GMT + 1(這是系統的本地時間(TZ)),我需要做什麼改變?
由於提前,
安德斯
使用此功能:如何在Perl中更改日期時間值的時區?
perl -e 'use Time::Local; print timelocal("00","00","00","01","01","2000"),"\n";'
它會返回一個epochtime - 但只有在格林尼治標準時間 - 如果我想要的結果在GMT + 1(這是系統的本地時間(TZ)),我需要做什麼改變?
由於提前,
安德斯
只有一個基於UTC的epochtime的標準定義,而不是不同時區的不同epochtimes。
如果你想找到offset between gmtime and localtime,使用
use Time::Local;
@t = localtime(time);
$gmt_offset_in_seconds = timegm(@t) - timelocal(@t);
你只需要設置時區。嘗試:
env TZ=UTC+1 perl -e 'use Time::Local; print timelocal("00","00","00","01","01","2000"),"\n";'
TLA時區不明確,定義不清。最好使用[zoneinfo](http://en.wikipedia.org/wiki/Olson_database)名稱:'TZ = Europe/Berlin perl ...' – daxim 2010-02-01 14:18:25
以下是直接鏈接到[有效時區列表字符串](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)aka'Zone.tab'。 – 2017-01-09 12:55:08
Time::Local::timelocal
是localtime
倒數。其結果將是在主機的本地時間:
$ perl -MTime::Local -le \ 'print scalar localtime timelocal "00","00","00","01","01","2000"' Tue Feb 1 00:00:00 2000
你想對應於該localtime
的gmtime
?
$ perl -MTime::Local' -le \ 'print scalar gmtime timelocal "00","00","00","01","01","2000"' Mon Jan 31 23:00:00 2000
你想它周圍的其他方式,對應於該gmtime
的localtime
?
$ perl -MTime::Local -le \ 'print scalar localtime timegm "00","00","00","01","01","2000"' Tue Feb 1 01:00:00 2000
投票,很好的信息。謝謝。 – Anders 2010-02-01 15:16:34
雖然Time :: Local是一個合理的解決方案,但您最好使用更現代的DateTime面向對象模塊。以下是一個示例:
use strict;
use DateTime;
my $dt = DateTime->now;
print $dt->epoch, "\n";
對於時區,可以使用DateTime :: TimeZone模塊。
use strict;
use DateTime;
use DateTime::TimeZone;
my $dt = DateTime->now;
my $tz = DateTime::TimeZone->new(name => "local");
$dt->add(seconds => $tz->offset_for_datetime($dt));
print $dt->epoch, "\n";
CPAN鏈接:
use DateTime;
my $dt = DateTime->now;
$dt->set_time_zone('Europe/Madrid');
的其他例子基於DateTime::Format::Strptime
use strict;
use warnings;
use v5.10;
use DateTime::Format::Strptime;
my $s = "2016-12-22T06:16:29.798Z";
my $p = DateTime::Format::Strptime->new(
pattern => "%Y-%m-%dT%T.%NZ",
time_zone => "UTC"
);
my $dt = $p->parse_datetime($s);
$dt->set_time_zone("Europe/Berlin");
say join ' ', $dt->ymd, $dt->hms; # shows 2016-12-22 07:16:29
檢查這些: [http://www.bestofperl.com/how -tos/timezone-conversion-date-time](http://www.bestofperl.com/how-tos/timezone-conversion-date-time)[http:// w (http://www.bestofperl.com/how-tos/parsing-datetime-strings) – Pradeep 2011-12-08 05:19:25