【发布时间】:2009-08-25 08:22:54
【问题描述】:
谁能帮助我如何在 Perl 中将此日期格式“Mon, 24 Aug 2009 17:00:44 +0800”转换为类似的“2009-08-24 17:00:44”?我一直在 CPAN 中浏览模块,但仍然无法找到我想要的东西。第一种格式是使用 Mail::POP3Client 从电子邮件帐户中检索的。另一个来自数据库中的查询。我的目的是比较这两个日期,但如果它们的格式不同,它将不起作用.. 有什么建议吗? =)
【问题讨论】:
谁能帮助我如何在 Perl 中将此日期格式“Mon, 24 Aug 2009 17:00:44 +0800”转换为类似的“2009-08-24 17:00:44”?我一直在 CPAN 中浏览模块,但仍然无法找到我想要的东西。第一种格式是使用 Mail::POP3Client 从电子邮件帐户中检索的。另一个来自数据库中的查询。我的目的是比较这两个日期,但如果它们的格式不同,它将不起作用.. 有什么建议吗? =)
【问题讨论】:
我会使用DateTime::Format::Strptime 将日期转换为 DateTime 对象,然后要求它提供所需的日期表示。例如:
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;
【讨论】:
我会使用Date::Calc
拆分字符串以获得所需的值并使用 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);
【讨论】:
如果您确定来自您的 POP3 客户端的时间戳格式不会改变,那么我建议您在数据库查询本身中转换格式。您没有提到您使用的数据库,但我使用的所有数据库(Oracle、PostgreSQL、MySQL)都具有在您的选择语句中为您提供任何格式的函数。
如果您告诉我们您使用的是什么数据库,我可以告诉您时间戳格式化函数是什么。
【讨论】: