views:

413

answers:

3

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???
}
+2  A: 

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/

draegtun
Thanks for the tip, look at my edit
Phill Pafford
this led me to my solution, see UPDATE. Thanks again
Phill Pafford
No probs. However I'm not sure what your "Is this correct?" edit is referring to? If no time zone is provided in the date/time string being parsed then your local TZ is assumed for it. The $dt->set_time_zone() then allows you to see the DateTime object you have but from a different timezone perspective. Hope that makes sense!
draegtun
+3  A: 
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.

jamessan
+2  A: 

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

Ether
Very unprecise answer.
daxim
@daxim: the question that I answered was very vague (if you look in the edit history, it was only one line).
Ether
@daxim: please check again, working code and reference added. Today has been a bad day for me for downvotes and I'd like to fix that! :)
Ether