2

我正在将数据从文本文件移动到数据库。文本文件的日期格式为“10 月 29 日”和“11 月 1 日”(10 月和 11 月是该文件中仅有的 2 个月)。我会将日期保存到 mysql 数据库中。如何在不手动操作的情况下将此格式转换为日期字段(假设为 2012 年)?

4

3 回答 3

1

以下应该有效,但是可能会进行优化:

$date = 'Oct 29';
list($month, $day) = explode(' ',$date);
$mysql_date = date('Y-m-d H:i:s', strtotime("$day $month 2012"));

您也许可以摆脱:

$date = 'Oct 29';
$mysql_date = date('Y-m-d H:i:s', strtotime("$date 2012"));

尽管您需要在您运行的任何版本的 php 上测试后者。

于 2012-11-04T01:07:22.303 回答
1
$str = 'Oct 29';
$str = strtotime("$str " . date('Y'));
// add the currect year and convert it into Unix timestamp
$formatted = date('Y-m-d H:i:s',$str);
// then convert it into MySQL datetime format
echo $formatted;
于 2012-11-04T01:11:55.093 回答
1

$array as $item['datefield']在没有看到您的文本文件的情况下,假设年份为 2012 年,一个包含并且您希望仅在 php 中实现日期转换的数组:

foreach ($array as $item) {
   // Format other vars...
   $insert_date = date("Y-m-d", strtotime($item['datefield']." 2012"));

 $query_insert = "
  INSERT INTO table_name (column1, column2, datefield,...)
  VALUES ($item['value1'], $item['value2'], $insert_date,...)
 ";
}

格式化没有什么意义,yyyy-mm-dd H:m:s因为您的日期字段中没有它...

于 2012-11-04T01:16:31.347 回答