views:

281

answers:

3

Code would be nice but a point in the right direction is good as well.

CPAN? RegEx?

I've seen both ways

"yyyy-MM-dd'T'HH:mm:ssZ";

"yyyy-MM-ddTHH:mm:ssZ";

A: 

Use both. Use a RegEx to split the input string into individual components (Year, Month, Day, etc...) then use Date::Calc http://search.cpan.org/~stbey/Date-Calc-6.3/lib/Date/Calc.pod

(I don't know what the 'T' and the 'Z' in "yyyy-MM-dd'T'HH:mm:ssZ" means so I'm very casually ignoring it ;)

if( $inStr =~ /(\d\d\d\d)-(\d{1,2})-(\d{1,2}) (\d{1,2})\:(\d\d)\:(\d\d)/ ) {
    $year = $1;
    $month = $2;
    $day = $3;
    $hour = $4;
    $min = $5;
    $sec = $6;
    if (check_date($year,$month,$day) && check_time($hour,$min,$sec)) {
        # looks good to me!
    }
}
LeguRi
No reason to write your own regexp when DateTime will do all of this for you.
Corey
You can't check the time separately. Some times are not available on some days.
brian d foy
Some times are not available on some days? I can't imagine when that would be the case... only thing which comes to mind is Daylight Savings, but that varies some based on locale, no?
LeguRi
+4  A: 

Depending on what you're doing, you might want to coerce your string into a DateTime object, e.g.:

use DateTime::Format::MySQL;
my $dt = DateTime::Format::MySQL->parse_datetime( '2003-01-16 23:12:01' );

Then you can easily output your time string in a different format, perform calculations with it, etc.

You didn't specify what is generating the string in that particular format, but there are DateTime::Format:: modules for a large number of input sources.

Ether
if I supply the datetime can I use this to convert it to UTC?
Phill Pafford
@Phil: you mean once you have the DateTime object constructed, can you convert between timezones? Absolutely: see the DateTime docs: http://search.cpan.org/perldoc/DateTime; the strftime() method will return a string in whatever format you specify.
Ether
+9  A: 

Ether is definitely on the right track with DateTime. Using DateTime, you can be sure that you have a time that actually exists, where something on Feb 29, 2000 might get by if you wrote the checks yourself.

Your format looks like an ISO8601 string. So, use DateTime::Format::ISO8601 to do your parsing.

use DateTime;
use DateTime::Format::ISO8601;

my $string = '2010-02-28T15:21:33Z';

my $dt = DateTime::Format::ISO8601->parse_datetime( $string );
die "Impossible time" unless $dt;

You could use other format modules, such as D::F::Strptime, but you will wind up recreating what ISO8601 formatter already does.

daotoad
DateTime must be one of the most useful and well designed modules ever written in any language, IMHO.
Leonardo Herrera