从Excel表格中将date和时间插入到DB中
我有Excel表有不同的列,但我需要在数据库(电子邮件,date和时间)添加一些特定的列。date从9/7/14开始,每件事情都很好,直到9/12/14,但是当一天到了13的时候,我会在1970-01-01 01:00:00进入数据库,当月份更改为10时,一切都很顺利,直到10/12/14再次形成13我得到1970-01-01 01:00:00进入数据库。
这是我的insert.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('Ymd H:i:s',strtotime($in_time)); $timestampOut = date('Ymd 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('Ymd H:i:s', strtotime($in_time));
因为$in_time
格式无效( 14/09/2014 14:50
)。 函数以m/d/Y
格式parsing14/09/2014
,但您试图将其用作d/m/Y
看到这里演示 。
简单的解决scheme是将date分隔符replace为-
,因为格式被改为dmY
,这是有效的,而strtotime()
将知道如何parsing它。 看到这里的演示 ,请在这里看RTM什么是有效的date格式。
parsing未知格式的最佳解决scheme它使用DateTime::createFromFormat()
方法:
$in_time = DateTime::createFromFormat('!d/m/YH:i', $in_time); echo $in_time->format('Ymd H:i:s');
演示