【发布时间】:2012-10-24 06:47:04
【问题描述】:
我正在将数据从文本文件移动到数据库。文本文件的日期格式为“10 月 29 日”和“11 月 1 日”(10 月和 11 月是该文件中仅有的 2 个月)。我会将日期保存到 mysql 数据库中。如何在不手动操作的情况下将此格式转换为日期字段(假设为 2012 年)?
【问题讨论】:
我正在将数据从文本文件移动到数据库。文本文件的日期格式为“10 月 29 日”和“11 月 1 日”(10 月和 11 月是该文件中仅有的 2 个月)。我会将日期保存到 mysql 数据库中。如何在不手动操作的情况下将此格式转换为日期字段(假设为 2012 年)?
【问题讨论】:
没有看到你的文本文件,假设年份为 2012,一个包含$array as $item['datefield'] 的数组,并且你想单独在 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 没什么意义,因为您的日期字段中没有它...
【讨论】:
以下应该可以工作,但是可能会进行优化:
$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 上测试后者。
【讨论】:
$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;
【讨论】: