开发者

How can I convert yyyy-mm-dd hh:mm:ss into UTC in Perl?

convert datetime format yyyy-mm-dd hh:mm:ss (Might be a string) 开发者_StackOverflowinto UTC, Looking into DateTime but I don't see how to parse the string?

UPDATE:

Is this working correctly?

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???
}


use DateTime::Format::ISO8601;
my $dt = DateTime::Format::ISO8601->parse_datetime('yyyy-mm-ddThh:mm:ss');

Use the DateTime::Format::ISO8601 module to parse that format and give you back a DateTime object.


Have a look at this SO question, How can I validate dates in Perl? for one answer.

There are also some nice DateTime helper modules on CPAN. For eg. DateTimeX::Easy which allows you to create DateTime objects like so:

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/


You need one of the parse methods in a DateTime::Format::* module.

Your string doesn't quite look like ISO8601 format (which is 'yyyy-mm-ddThh:mm:ss'), but it matches MySQL's formatting style:

use DateTime::Format::MySQL;
my $dt = DateTime::Format::MySQL->parse_datetime('2010-02-28 00:00:00');

print $dt->strftime("%Y %M %d %T");

produces:

2010 00 28 00:00:00

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜