【问题标题】:How can I convert yyyy-mm-dd hh:mm:ss into UTC in Perl?如何在 Perl 中将 yyyy-mm-dd hh:mm:ss 转换为 UTC?
【发布时间】:2010-01-20 19:58:33
【问题描述】:

将日期时间格式 yyyy-mm-dd hh:mm:ss(可能是字符串)转换为 UTC, 查看 DateTime 但我看不到如何解析字符串?

更新:

这是否正常工作?

require 5.002;

use strict;
use warnings;

use DateTime::Format::DateManip;

my $string = '2010-02-28 00:00:00';

my @dates = (
    $string
);

for my $date ( @dates ) {
    my $dt = DateTime::Format::DateManip->parse_datetime( $date );
    die "Cannot parse date $date, Please use a valid date in this format 'yyyy-mm-dd mm:hh:ss'"  unless defined $dt;
    print $dt."\n";
    $dt->set_time_zone( 'UTC' );
    print $dt."Z\n"; # Is this correct???
}

【问题讨论】:

    标签: perl datetime format utc


    【解决方案1】:
    use DateTime::Format::ISO8601;
    my $dt = DateTime::Format::ISO8601->parse_datetime('yyyy-mm-ddThh:mm:ss');
    

    使用DateTime::Format::ISO8601 模块解析该格式并返回一个DateTime 对象。

    【讨论】:

      【解决方案2】:

      看看这个 SO 问题,How can I validate dates in Perl? 一个答案。

      CPAN 上还有一些不错的 DateTime 帮助模块。例如。 DateTimeX::Easy 允许您像这样创建 DateTime 对象:

      use DateTimeX::Easy;
      
      my $a_date    = DateTimeX::Easy->new( '11/17/2008 12:01am' );
      
      my $tomorrow  = DateTimeX::Easy->new( 'tomorrow' );
      
      my $last_week = DateTimeX::Easy->new( 'last week' );
      

      /I3az/

      【讨论】:

      • 这使我找到了我的解决方案,请参阅更新。再次感谢
      • 没有问题。但是我不确定你的“这是正确的吗?”编辑指的是什么?如果正在解析的日期/时间字符串中未提供时区,则假定为您的本地 TZ。然后 $dt->set_time_zone() 允许您从不同的时区角度查看您拥有的 DateTime 对象。希望这是有道理的!
      【解决方案3】:

      您需要 DateTime::Format::* 模块中的一种解析方法。

      您的字符串看起来不太像 ISO8601 格式(即 'yyyy-mm-ddThh:mm:ss'),但它符合 MySQL 的格式样式:

      use DateTime::Format::MySQL;
      my $dt = DateTime::Format::MySQL->parse_datetime('2010-02-28 00:00:00');
      
      print $dt->strftime("%Y %M %d %T");
      

      产生:

      2010 00 28 00:00:00

      【讨论】:

      • @daxim:我回答的问题很模糊(如果你查看编辑历史,它只有一行)。
      • @daxim:请再次检查,添加了工作代码和参考。今天对我来说是糟糕的一天,我想解决这个问题! :)
      猜你喜欢
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      相关资源
      最近更新 更多