>我有Excel工作表,它有不同的列,但我需要在数据库中添加一些特定的列(电子邮件,日期和时间)。日期从 9 年 7 月 14 日开始,直到 9 年 12 月 14 日一切正常,但是当一天变成 13 到月底时,我将 1970-01-01 01:00:00 放入数据库,再次当月份更改为 10 时,一切都很好,直到 10/12/14 和再次形成 13 我将 1970-01-01 01:00:00 放入数据库。
这是我的插入.php代码
session_start();
$target_dir = $_SESSION["targetDir"];
$file_name = $_SESSION["fileName"];
ini_set('memory_limit', '512M');
require_once 'excel_reader2.php';
require_once 'dbConn.php';
$data = new Spreadsheet_Excel_Reader($target_dir);
for($i=0;$i<count($data->sheets);$i++) // Loop to get all sheets in a file.
{
switch ($i) {
case 1:
echo "<p class='font_p'>Rows in Sheet $i : " . count($data->sheets[$i]['cells'])."    " ;
$countWithHeader = count($data->sheets[$i]['cells']);
$finalCount = $countWithHeader - 1;
for ($j = 1; $j <= count($data->sheets[$i]['cells']); $j++) // loop used to get each row of the sheet
{
$data->sheets[$i]['cells'][$j][1];
$email = mysqli_real_escape_string($connection, $data->sheets[$i]['cells'][$j][1]);
$first_name = mysqli_real_escape_string($connection, $data->sheets[$i]['cells'][$j][2]);
$last_name = mysqli_real_escape_string($connection, $data->sheets[$i]['cells'][$j][3]);
$in_time = mysqli_real_escape_string($connection, $data->sheets[$i]['cells'][$j][5]);
$out_time = mysqli_real_escape_string($connection, $data->sheets[$i]['cells'][$j][6]);
$timestampIn = date('Y-m-d H:i:s',strtotime($in_time));
$timestampOut = date('Y-m-d H:i:s',strtotime($out_time));
$query = "INSERT INTO study_table (email,last_name,first_name,in_time,out_time)
VALUES ('".$email."','".$first_name."','".$last_name."','".$timestampIn."','".$timestampOut."')";
mysqli_query($connection, $query);
}
break;
case 2:
函数strtotime()
将在代码中返回false
:
$timestampIn = date('Y-m-d H:i:s', strtotime($in_time));
因为$in_time
格式无效(14/09/2014 14:50
)。函数将14/09/2014
解析为m/d/Y
格式,但您尝试将其用作d/m/Y
。有关演示,请参见此处。
简单的解决方案是将日期分隔符/
替换为-
,因为这样格式将更改为 d-m-Y
,这是有效的,strtotime()
知道如何解析它。请参阅此处进行演示,请在此处RTM以查看什么是有效的日期格式。
解析未知格式以使用DateTime::createFromFormat()
方法的最佳解决方案:
$in_time = DateTime::createFromFormat('!d/m/Y H:i', $in_time);
echo $in_time->format('Y-m-d H:i:s');
演示