tags:

views:

185

answers:

3

Can anyone help me how to convert this date format "Mon, 24 Aug 2009 17:00:44 +0800" into something like this, "2009-08-24 17:00:44" in Perl? I've been browsing in CPAN for modules, but still I wasn't able to find what I was looking for. The first format is retrieved from an email account using Mail::POP3Client. The other one is from a query in database. My aim here is to compare these two dates, but it won't work if they are in different format.. Any suggestions pls? =)

+1  A: 

I would use Date::Calc

Split the string to get the needed values and use Decode_Month("Aug")

use strict;
use warnings;
use Date::Calc qw(:all);

my $datetime = 'Mon, 24 Aug 2009 17:00:44 +0800';

# get each part
my (undef, $day, $month_text, $year, $time, undef) = split('/,?\s/', $datetime);

my $month = Decode_Month($month_text);

# put together in wanted format
my $newdatetime = sprintf("%04d-%02d-%02d $time", $year, $month, $day);
Nifle
split /,?\s/ avoids the previous s///
larelogio
thanks, fixed it
Nifle
+7  A: 

I'd use DateTime::Format::Strptime to convert the date into a DateTime object, then ask it to provide the desired representation of the date. e.g.:

my $parser = DateTime::Format::Strptime->new(pattern => '%a, %d %b %Y %T %z');
my $dt = $parser->parse_datetime($original_timestamp);

# Postgres-format timestamp for db storage
my $pg_timestamp = DateTime::Format::Pg->format_datetime($dt);

# Epoch timestamp for if I'm going to do the comparison in code
my $epoch = $dt->epoch;
Dave Sherohman
A: 

If you are certain that the Timestamp Format from your POP3 client will not change, then I would suggest converting the format in the database query itself. You have not mentioned what database you use, but all the ones that I have used (Oracle, PostgreSQL, MySQL) have functions that give you any format you want in your select statement.

If you tell us what database you are using, I can tell you what the timestamp formatting functions are.

Gurunandan