如何在 Perl 中更改日期时间值的时区?
使用此函数:
perl -e 'use Time::Local; print timelocal("00","00","00","01","01","2000"),"\n";'
它将返回一个纪元 - 但仅限于 GMT - 如果我想要 GMT+1 的结果(即系统本地时间(TZ)),我需要更改什么?
预先感谢,
安德斯
Using this function:
perl -e 'use Time::Local; print timelocal("00","00","00","01","01","2000"),"\n";'
It will return an epochtime - but only in GMT - if i want the result in GMT+1 (which is the systems localtime(TZ)), what do i need to change?
Thanks in advance,
Anders
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
epochtime 只有一种基于 UTC 的标准定义,并且不同时区没有不同的 epochtime。
如果您想找到 gmtime 和 localtime 之间的偏移,使用
There is only one standard definition for epochtime, based on UTC, and not different epochtimes for different timezones.
If you want to find the offset between gmtime and localtime, use
另一个基于 DateTime::Format::Strptime 的示例
An other example based on DateTime::Format::Strptime
虽然 Time::Local 是一个合理的解决方案,但您最好使用更现代的 DateTime 面向对象模块。下面是一个示例:
对于时区,您可以使用 DateTime::TimeZone 模块。
CPAN 链接:
DateTime
While Time::Local is a reasonable solution, you may be better off using the more modern DateTime object oriented module. Here's an example:
For the timezones, you can use the DateTime::TimeZone module.
CPAN Links:
DateTime
您只需设置时区即可。尝试:
You just need to set the timezone. Try:
Time::Local::timelocal
是localtime
的倒数。结果将采用您主机的当地时间:您想要与该
本地时间
相对应的gmtime
吗?您是否想要相反的方式,即与
gmtime
相对应的localtime
?Time::Local::timelocal
is the inverse oflocaltime
. The result will be in your host's local time:Do you want the
gmtime
that corresponds to thatlocaltime
?Do you want it the other way around, the
localtime
that corresponds to thatgmtime
?算法
如果要将时间值从一个时区更改为另一个时区,则必须能够指示两个时区。
毕竟,如果您设置是否要将
“12:30”
转换为GMT或美国/东部或委内瑞拉时间,这意味着添加/减去一些小时或小时和分钟,您需要知道哪个时区是开始时间zone,否则,计算将不知道要加多少或减多少。如果您使用
DateTime->now;
,时区默认为系统时间,这可能不是您想要转换的时区。在下面的代码中,我演示了如何将日期时间对象初始化为正确的起始时区 (
fromtimezone
) 以及如何将该时间转换为结束时区 (totimezone
)...工作代码
I无法在线找到安装了
DateTime
CPAN 模块的 Perl 沙箱。输出:
The Algorithm
If you want to change a time value from one timezone to another timezone, you must be able to indicate both timezones.
After all, if you set if you want to convert
"12:30"
to GMT or US/Eastern or Venezuelan time, which means adding/subtracting some amount of hours or hours and minutes, you need to know what timezone is the starting time zone, otherwise, the calculation won't know how much to add or subtract.If you use
DateTime->now;
, the timezone is defaulted to the system-time, which may not be the timezone you want to convert from.In the below code, I demonstrate how to initialize the datetime object to the right starting timezone (
fromtimezone
) and how to convert that time to the ending timezone (totimezone
)...Working Code
I could not find a Perl sandbox online with the
DateTime
CPAN module installed.Output: