php使用phpexcel导入excel时,如果某列使用的是excel的日期时间格式,比如2019/12/18 20:00:00,如果数据库存储的是时间戳,而在导入时直接使用了strtotime(),则导入的时间是不正确的,而且是空的,因为读取出来根本不是一个时间戳,而是类似43817.833333333这样的数据,需要转一下,这里有个公式:
echo gmdate('Y-m-d H:i:s', (43817.833333333 - 25569) * 3600 * 24);
之所以用gmdate,因为excel是使用的格林威治时间。
如果是存时间戳:
$theTime = strtotime(gmdate('Y-m-d H:i:s', $theTime))
网上大部分到这一步就完了,我就被坑过,还是比如2019/12/18 20:00:00这个时间,转为时间戳后导入数据库,在从数据库读取出来转为时间,结果却是2019-12-18 19:59:59,但同样的方式,在其他时间上却是正确的,比如:2019-12-18 19:00:00;
我们把这2个时间输出来看看
$theTime = ($data[5] - 25569) * 3600 * 24;
echo $data[5] - 25569 . '<br/>';
echo $theTime . '<br/>';
echo gmdate('Y-m-d H:i:s', $theTime) . '<br/>';
echo strtotime(gmdate('Y-m-d H:i:s', $theTime)) . '<br/>';
echo '--------------------------<br/>';
$data[5]是从excel读取数据
2019-12-18 19:00:00和2019-12-18 19:59:59的输出如下
18248.791666667
1576695600
2019-12-18 19:00:00
1576666800
--------------------------
43817.833333333
18248.833333333
1576699200
2019-12-18 19:59:59
1576670399
,在细分下,采用普通计算和高进度计算看看结果:
$theTime = ($data[5] - 25569) * 3600 * 24;
echo $data[5] - 25569 . '<br/>';
echo bcsub($data[5], 25569, 9) . '<br/>';
echo ($data[5] - 25569) * 86400 . '<br/>';
echo bcmul(($data[5] - 25569), 86400, 9) . '<br/>';
echo $theTime . '<br/>';
echo gmdate('Y-m-d H:i:s', $theTime) . '<br/>';
echo strtotime(gmdate('Y-m-d H:i:s', $theTime)) . '<br/>';
echo '--------------------------<br/>';
结果如下
18248.791666667
18248.791666667
1576695600
1576695600.000028800
1576695600
2019-12-18 19:00:00
1576666800
--------------------------
18248.833333333
18248.833333333
1576699200
1576699199.999971200
1576699200
2019-12-18 19:59:59
1576670399
相信看到这个结果,就应该知道问题在哪里了,如果使用四舍五入计算:
$theTime = round(($data[5] - 25569) * 3600 * 24);
echo $data[5] - 25569 . '<br/>';
echo bcsub($data[5], 25569, 9) . '<br/>';
echo ($data[5] - 25569) * 86400 . '<br/>';
echo bcmul(($data[5] - 25569), 86400, 9) . '<br/>';
echo round($theTime) . '<br/>';
echo gmdate('Y-m-d H:i:s', $theTime) . '<br/>';
echo strtotime(gmdate('Y-m-d H:i:s', $theTime)) . '<br/>';
echo '--------------------------<br/>';
结果如下
18248.791666667
18248.791666667
1576695600
1576695600.000028800
1576695600
2019-12-18 19:00:00
1576666800
--------------------------
18248.833333333
18248.833333333
1576699200
1576699199.999971200
1576699200
2019-12-18 20:00:00
1576670400