I'm从Excel文件导入Mysql,但结果是1970-01-01


I'm Import to Mysql from Excel files, but the results are 1970-01-01

我从Excel文件导入Mysql,但结果是1970-01-01,这是我的代码:

// server info
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'agenda';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
?>
<?php
require 'classes/phpexcel.php';
require_once 'classes/phpexcel/iofactory.php';
$inputFileName  = 'database/sql/agenda.xlsx';
$inputFileType  = 'Excel2007';
$objReader      = PHPExcel_IOFactory::createReader("$inputFileType");
$objReader->setReadDataOnly(true);
$objPHPExcel    = $objReader->load("$inputFileName");
$objWorksheet   = $objPHPExcel->getActiveSheet();
$highestRow     = $objWorksheet->getHighestRow();
$highestColumn  = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
// view in table
echo '<table>' . "'n";
for ($row = 1; $row <= $highestRow; ++$row) {
    echo '<tr>' . "'n";
    for ($col = 0; $col <= $highestColumnIndex; ++$col) {
        echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "'n";
    }
    echo '</tr>' . "'n";
}
echo '</table>' . "'n";
//input to mysql
for($row = 2; $row <= $highestRow; ++$row) {
    for($col = 0; $col < $highestColumnIndex; ++$col) {  
        $rows[$col] = $objWorksheet->getCellByColumnAndRow($col, $row); 
    }
    $id   ="$rows[0]";
    $ts   ="$rows[1]";
    $pd   ="$rows[2]";
    $get_data1  = "$rows[3]";
    $st   = date("Y-m-d", strtotime ($get_data1));
    $stm  ="$rows[4]";
    $get_data2  ="$rows[5]";
    $et   = date("Y-m-d", strtotime ($get_data2));
    $etm  ="$rows[6]";
    $g    ="$rows[7]";
    $w    ="$rows[8]";
    // Prepared Statement
    $stmt = $mysqli->prepare("INSERT INTO `keyin` VALUES ('$id', '$ts', '$pd', '$st', '$stm', '$et', '$etm', '$g', '$w')");
    //Prepared Statement Bound$stmt->bind_param('sssssssss', $id, $ts, $pd, $st, $stm, $et, $etm, $g, $w);     

    //Prepared Statement Executed 
    $stmt->execute();
    printf("%s Row Inserted.'n", $stmt->affected_rows);
    //Prepared Statement Closed
    $stmt->close();
    // If you don't want to use prepared statement, you can use this one
    $mysqli->query("INSERT INTO users (Username,Email,Gender,Country) VALUES ('$rows[0]', '$rows[1]', '$rows[2]', '$rows[3]')");
}
$mysqli->close();

由于excel计算从1900-01-01开始的天数,所以不能使用strtotime()。

你需要做的是把excel的天转换成秒。

$unix = ($get_data1 - 25569) * 86400; 
$st = date("Y-m-d", $unix);

你的excel值~42000小于一天的秒数(86400),因此你在php中得到1970-01-01。
如果您在php代码中添加时间,您将看到时间将在1970年1月1日中午左右。

https://3v4l.org/teI1F

try this:

$st = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($get_data1));