我们目前正在使用以下列格式提供日期时间的第三方API:
Sat Mar 06 09:00:00 ICST 2010
Fri Feb 19 19:30:00 JDT 2010
Fri Feb 19 19:30:00 PST 2010
但是,我们希望在标准日期时间字段中将这些日期时间对象存储在MysqL中,该字段需要以下格式:
YYYY-MM-DD HH:MM:SS
现在我们正在使用以下代码报告某些时区的错误,例如KDT,JDT和ICST:
use Date::Manip;
use DateTime;
use DateTime::Format::DateManip;
my $date = ParseDate($time);
$date = DateTime::Format::DateManip->parse_datetime($date);
eval{ $time = $date->strftime("%Y-%m-%d %H:%M:%S"); };
您能否建议更好地实现上面的Perl代码,将日期时间对象从API转换为我们服务器上的正确格式和时间,以便插入MysqL日期时间字段?
在此先感谢您的帮助和帮助咨询!
最佳答案
将时间存储在GMT内部.在GMT中做所有操作.然后在最后一刻,就像您要向用户显示结果一样,然后转换为用户的本地时间.
原文链接:https://www.f2er.com/mysql/433327.html我建议使用Date::Parse,但你必须增加其时区偏移,因为它目前没有印度支那夏令时和日本夏令时.
#! /usr/bin/perl
use warnings;
use strict;
use Date::Format;
use Date::Parse;
# add timezone offsets
$Time::Zone::Zone{icst} = +7*3600;
$Time::Zone::Zone{jdt} = +9*3600;
while (Failed conversion for $_\n"),next
unless defined(my $time_t = str2time $_);
my @t = gmtime($time_t);
print $_," => ",strftime("%Y-%m-%d %H:%M:%S",@t),"\n";
}
__DATA__
Sat Mar 06 09:00:00 ICST 2010
Fri Feb 19 19:30:00 JDT 2010
Fri Feb 19 19:30:00 PST 2010
输出:
Sat Mar 06 09:00:00 ICST 2010 => 2010-03-06 02:00:00 Fri Feb 19 19:30:00 JDT 2010 => 2010-02-19 10:30:00 Fri Feb 19 19:30:00 PST 2010 => 2010-02-20 03:30:00
要支持您想要的查询,请将时间存储在GMT加上偏移量(即从GMT到API的本地时间).请注意,下面的代码假设如果str2time可以解析给定时间,strptime也可以.将循环更改为
my @dates;
while (Failed conversion for $_\n"),next
unless defined(my $time_t = str2time $_);
my $zone = (strptime $_)[-1];
my @t = gmtime($time_t);
push @dates => [ strftime("%Y-%m-%d %H:%M:%S",sprintf("%+03d:%02d",int($zone / 3600),int($zone % 3600) / 60),$_
];
}
收集时间后,将其呈现为sql:
print "DROP TABLE IF EXISTS dates;\n","CREATE TABLE dates (date DATETIME,offset CHAR(6));\n","INSERT INTO dates (date,offset) VALUES\n",join(",\n\n" =>
map(" -- $_->[2]\n" .
" ('$_->[0]','$_->[1]')",@dates)),";\n","SELECT CONVERT_TZ(date,'+00:00',offset) FROM dates;\n"
输出是
DROP TABLE IF EXISTS dates;
CREATE TABLE dates (date DATETIME,offset CHAR(6));
INSERT INTO dates (date,offset) VALUES
-- Sat Mar 06 09:00:00 ICST 2010
('2010-03-06 02:00:00','+07:00'),-- Fri Feb 19 19:30:00 JDT 2010
('2010-02-19 10:30:00','+09:00'),-- Fri Feb 19 19:30:00 PST 2010
('2010-02-20 03:30:00','-08:00');
SELECT CONVERT_TZ(date,offset) FROM dates;
我们可以将它传递给MysqL:
$./prog.pl | MysqL -u username -D dbname CONVERT_TZ(date,offset) 2010-03-06 09:00:00 2010-02-19 19:30:00 2010-02-19 19:30:00