Вопрос

How can I convert

12/22/13 21:48:06

to the MySQL DATETIME format

YYYY-MM-DD HH:MM:SS
Это было полезно?

Решение 2

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";

Or if you don't need any validation,

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

or

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

Другие советы

DateTime::Format::DBI can convert DateTime objects to the appropriate string representation for the database engine you're using. This is nice because it allows you to switch RDBMS's without having to rewrite your date parsing code.

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

This may be overkill for what you're working on but could be handy for projects where you need to connect to multiple types of database simultaneously, for example. IBM DB2, Microsoft SQL, MySQL, Oracle, PostgreSQL, SQLite, and Sybase are currently supported.

Another possibility for parsing and formatting dates is Time::Piece, which has been a core module since Perl 5.9:

use Time::Piece;

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

Output:

2013-12-22 21:48:06
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top