gpt4 book ai didi

windows - 如何在 Windows 上使用 Perl 优雅地打印 %z(时区)格式?

转载 作者:可可西里 更新时间:2023-11-01 13:26:26 26 4
gpt4 key购买 nike

How do I elegantly print the date in RFC822 format in Perl? 的分支,但特定于 Windows。

在 window 上:

    C:\> perl -MPOSIX    print strftime('%z', localtime()),"\n";

Yields:

    Central Daylight Time

I was expecting:

    -0500

As anyone would on a Linux system. How can I get the "-0500" on Windows?

UPDATE:

Is this really terrible to do in its place? (Assuming I'm not allowed to install DateTime or package it in any way)

C:\> perl -MPOSIX
sub tzoffset {
my $t = time();
my $utc = mktime(gmtime($t));
my $local = mktime(localtime($t));

return ($local - $utc);
}

sub zformat {
my ($tzoffset) = @_;
my $z = '';
if ($tzoffset < 0) {
$z .= '-';
$tzoffset *= -1;
}
my $hours = floor($tzoffset / 60 / 60);
my $minutes = $tzoffset - $hours * 60 * 60;
$z .= sprintf('%02d%02d', $hours, $minutes);
return $z;
}

print zformat(tzoffset()),"\n";

我注意到的问题是这返回 -0600-0500(我期望的),但我的猜测是由于 DST 计算或者其他的东西?我主要是在寻找一个合适的近似值,但我不明白为什么 mktime() 正在玩 DST?

更新:

发现如果您只是手动强制关闭 DST,tzoffset() 可以在 DST 方面更加“稳定”。

sub tzoffset {
my $t = time();
my $utc = mktime(gmtime($t));
my @tmlocal = localtime($t);
$tmlocal[8] = 0; # force dst off, timezone specific
my $local = mktime(@tmlocal);

return ($local - $utc);
}

这样,无论您是否是夏令时,它总是会返回 -0500,这正是您希望从 %z 获得的结果。

最佳答案

我认为你得到前者的原因是因为

  1. %z 是特定于 Linux 的
  2. 在 Windows 上,它以某种方式对您不区分大小写,而是选择大写字母 Z。

来自手册页:

%Z    Time zone name or abbreviation, or no bytes if no time
zone information exists.

此外,“%z”似乎是特定于 Linux 的——在 Solaris 上也不起作用:

$ perl -MPOSIX -e 'print strftime("%z", localtime()),"\n"' 
%z
$ perl -MPOSIX -e 'print strftime("%Z", localtime()),"\n"'
EDT

而在 Linux 上我得到:

$ perl -MPOSIX -e 'print strftime("%z", localtime()),"\n"' 
-0400

如果你有DateTime::Format安装后,我认为它可能支持基于 POD 的 %z。我还没有安装它,所以还不能测试

DateTime 也可以在没有 DateTime::Format 的情况下支持它。

关于windows - 如何在 Windows 上使用 Perl 优雅地打印 %z(时区)格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2632104/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com