如何将日期字符串转换为MySQL DATETIME?

时间:2013-12-26 15:47:11

标签: perl datetime-format

如何转换

12/22/13 21:48:06

到MySQL DATETIME格式

YYYY-MM-DD HH:MM:SS

3 个答案:

答案 0 :(得分:5)

DateTime::Format::DBI可以将DateTime个对象转换为您正在使用的数据库引擎的相应字符串表示形式。这很好,因为它允许您切换RDBMS而无需重写日期解析代码。

use DateTime;
use DateTime::Format::DBI;
use DateTime::Format::Strptime;
use DBI;

my $dbh = DBI->connect( ... ) or die $DBI::errstr;

my $date = '12/22/13 21:48:06';
my $str_parser = DateTime::Format::Strptime->new(pattern => '%D %T');

# Parse string into a DateTime object
my $dt = $str_parser->parse_datetime($date);

my $db_parser = DateTime::Format::DBI->new($dbh);

$dbh->do("INSERT INTO table VALUES (?)", undef,
         $db_parser->format_datetime($dt));

# For MySQL, inserts 2013-12-22 21:48:06

对于您正在处理的内容而言,这可能过于苛刻,但对于需要同时连接到多种类型数据库的项目来说可能非常方便。目前支持IBM DB2,Microsoft SQL,MySQL,Oracle,PostgreSQL,SQLite和Sybase。

答案 1 :(得分:1)

my ($m,$d,$y,$T) = $orig_dt =~ m{^(\d\d)/(\d\d)/(\d\d) (\d\d:\d\d:\d\d)\z}
   or die "Error";

my $mysql_dt = "20$y-$m-$d $T";

或者,如果您不需要任何验证,

my ($m,$d,$y,$T) = split(/[\/ ]/, $orig_dt);
my $mysql_dt = "20$y-$m-$d $T";

my $mysql_dt = sprintf('20%3$s-%1$s-%2$s %4$s', split(/[\/ ]/, $orig_dt));

答案 2 :(得分:1)

解析和格式化日期的另一种可能性是Time::Piece,这是自Perl 5.9以来的核心模块:

use Time::Piece;

my $t = Time::Piece->strptime('12/22/13 21:48:06', '%D %T');
print $t->strftime('%F %T');

输出:

2013-12-22 21:48:06