Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) into 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???
}
like image 825
Phill Pafford Avatar asked Dec 05 '25 10:12

Phill Pafford


2 Answers

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.

like image 198
jamessan Avatar answered Dec 07 '25 12:12

jamessan


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/

like image 32
draegtun Avatar answered Dec 07 '25 12:12

draegtun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!