我想获得自纪元以来给定的微秒数,以本地时间与gmtime之间的小时数表示。到目前为止,我有这样的事情
# Microseconds since Epoch
my $msec = 555329743301750;
# Convert to seconds
my $sec = $msec/1000000;
my $val = (POSIX::mktime(localtime $sec) - POSIX::mktime(gmtime $sec)) / 60 / 60;
print "$val\n";
1)我得到的输出是-6。(CST本地时间)但是我期望-5。我期望的行为类似于运行bash命令的结果
`date -d 20190514 "+%z"`;
2)长话短说,如何计算与perl中的date -d 20190514 "+%z"
类似的偏移量?
答案 0 :(得分:0)
使用核心Time::Piece:
use strict;
use warnings;
use Time::Piece;
# Microseconds since Epoch
my $usec = 555329743301750;
# Convert to seconds
my $sec = $usec/1000000;
my $offset = localtime($sec)->tzoffset / 3600;
如果按照我在your other question上显示的方式构造它们,Time :: Moment和DateTime也可以返回此值。
my $offset = $time_moment->offset / 60;
my $offset = $datetime->offset / 3600;
您也可以从日期创建这些对象,但是它当然会为您提供当天的午夜(当地时间)的偏移量。
use Time::Piece;
my $time = localtime->strptime('20190514', '%Y%m%d');
use Time::Moment;
use Role::Tiny ();
my $class = Role::Tiny->create_class_with_roles('Time::Moment', 'Time::Moment::Role::TimeZone');
my $time = $class->new(year => 2019, month => 5, day => 14)->with_system_offset_same_local;
use DateTime;
my $time = DateTime->new(year => 2019, month => 5, day => 14, time_zone => 'local');
答案 1 :(得分:0)
这将为您提供与Linux“%z”格式相同的[+-] HHMM格式:
use POSIX qw[mktime];
my $tz = (localtime time)[8] * 60 - mktime(gmtime 0) / 60;
$tz = sprintf "%+03d%02d\n", $tz / 60, abs($tz) % 60;
如果您只想以小时为单位,则可以执行以下操作:
my $tz_offset_hours = (localtime time)[8] - mktime(gmtime 0)) / 3600;
奖金::以下子例程将返回带有时区偏移和微秒的完整时间戳,如“ YYYY-MM-DD HH:MM:SS.nnnnnn [+-] HHMM”:< / p>
use POSIX qw[mktime strftime];
use Time::HiRes qw[gettimeofday];
sub timestamp () {
my @now = gettimeofday;
my $tz = (localtime $now[0])[8] * 60 - mktime(gmtime 0) / 60;
my $ts = strftime("%Y-%m-%d %H:%M:%S", localtime $now[0]);
return sprintf "%s.%06d %+03d%02d", $ts, $now[1], $tz / 60, abs($tz) % 60;
}