perl - 如何在 Perl 中解析日期和转换时区?

标签 perl datetime parsing date timezone

我用过localtime Perl 中的函数来获取当前日期和时间,但需要解析现有日期。我有以下格式的 GMT 日期:“20090103 12:00”我想将其解析为我可以使用的日期对象,然后将 GMT 时间/日期转换为我当前的时区,该时区目前是东部标准时间.因此,我想将“20090103 12:00”转换为“20090103 7:00”任何有关如何执行此操作的信息将不胜感激。

最佳答案

因为 Perl 内置的日期处理接口(interface)有点笨重,而且你最终会传递大约六个变量,所以更好的方法是使用 DateTimeTime::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;

为了对比,这是手动方式。

由于格式是固定的,正则表达式就可以了,但如果格式发生变化,您将不得不调整正则表达式。
my($year, $mon, $day, $hour, $min) = 
    $date =~ /^(\d{4}) (\d{2}) (\d{2})\ (\d{2}):(\d{2})$/x;

然后将其转换为 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);

然后回到你的本地时间。
(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;

关于perl - 如何在 Perl 中解析日期和转换时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/411740/

相关文章:

perl - 在 Perl 中使用 MyParser 从 HTML 标签获取内容

perl - 使用基于 WSDL 的 SOAP::Lite

python - 计算 Pandas 中的独特广告展示次数

perl - 在 Template Toolkit 中格式化输出的时间戳字段

perl - Perl 模块 autodie 和 Fatal 有什么区别?

ruby-on-rails - 在 Ruby on Rails 中,DateTime、Timestamp、Time 和 Date 之间有什么区别?

c# - 如何为每个线程设置时区?

parsing - 自动将 MIDI 文件分割成数据集的短语

Python:基于绝对XPath解析HTML元素

java - 如何使用 Apache Daffodil 的 DataProcessor.unparse() 方法来重建原始解析消息?