2013-06-29 31 views
0

我似乎無法找到一種方法來格式化perl中的字符串以在MySQL DateTime()字段中使用。SQL和perl時間格式

my $time = "Sat Jun 29 11:20:28 2013 -0400" 

,我需要時間,格式,因此它可以被輸入到MySQL的日期時間()字段

Format: YYYY-MM-DD HH:MM:SS 

我打算進入這個用perl的mysql模塊

$createQuery = "INERT INTO something (dated) Values(?) "; 
    $sqlQuery = $dbh->prepare($createQuery); 
    $sqlQuery->execute($time); 
+0

也許這些[鏈接]的一個(http://stackoverflow.com/search?q=%5Bperl% 5DTime%3A%3Piece + strptime)將有所幫助。 –

回答

1

你不你不必自己做任何格式化。

$time = time; 
$createQuery = "INSERT INTO something (dated) Values(FROM_UNIXTIME(?)) "; 
$sqlQuery = $dbh->prepare($createQuery); 
$sqlQuery->execute($time); 

如果你真的需要一個字符串,您的數據源不是一個UNIX時間戳,只需使用任何formats that MySQL understands的。

$time = '2013-06-29 18:50:00'; 
$createQuery = "INSERT INTO something (dated) Values(FROM_UNIXTIME(?)) "; 
$sqlQuery = $dbh->prepare($createQuery); 
$sqlQuery->execute($time); 
+0

謝謝,這工作。我剛寫了一個函數來正確格式化它,並且它工作正常 –

1

您可以使用核心模塊Time::Piece 5.9以來這一直是Perl的核心部分:corelist

use Time::Piece; 
my $time = q(Sat Jun 29 11:20:39 2013 -0400); 
my $t = Time::Piece->strptime($time, '%a %b %d %H:%M:%S %Y %z'); 
print $t->strftime("%Y-%m-%d %H:%M:%S\n"); 
0

如果你沒有perl的5.9,Date::Manip將整理您:

$date_as_mysql_likes = UnixDate(ParseDate($your_date_here), '%Y-%m-%d %H:%M:%S');