Jessie-candy

历史项目,使用的是Laravel:5.4版本,Excel插件使用maatwebsite/excel:2.1.30,导入Excel数据的时候发现,有一些日期接收的时候变成了数值类型,如43126.0

google一下,发现原来excel中表示日期的文本格式确实一组纯数字,而且这个纯数字就是一个偏移的值。这个偏移的值是距离1900/1/0 0:00:00的一个天数值2015/5/20的文本格式42144.6580671296正好是距离1900/1/0 0:00:00的天数。

那么距离1900/1/0 0:00:0043123天正好就是2018后的某一天。43123/365=118.xxx年1900+118=2018

因为PHPExcel中将所有的列解析成文本格式,读出的时间是距离1900-01-01的偏移天数。 即excel日期是从 1900-01-01 开始计算的(php 是从 1970-01-01),两者间有一个天数差 42144.6580671296。时间是格林威治时间

 
编写通用函数解决该问题:
 
if (!function_exists(\'str_to_date\')) {
    /**
     * (false|string) str_to_date_format : 将 "2017年7月10日" "2017.7.10" 转为标准的日期格式"2017-7-10"
     *
     * @param         $date
     * @param boolean $falseReturnNow 格式错误是否返回当前日期
     * @param string  $format
     *
     * @return false|string
     */
    function str_to_date_format($date, $falseReturnNow=true, $format=\'Y-m-d\') {
        if (!$falseReturnNow && !$date) {
            return null;
        }
        // 接收的日期如果是数值型则用PHPExcel的内置方法转换成时间戳
        if (is_numeric($date)) {
            $timestamp = \PHPExcel_Shared_Date::ExcelToPHP($date);
            return date($format, $timestamp);
        }
        $date = str_replace([\'号\', \'日\'], \'\', $date);
        $date = str_replace([\'年\', \'月\', \'.\', \'—\', \'——\', \'/\', \'-\', \'--\'], \'-\', $date);
        // 如果时间格式错误,是否需要返回当前时间
        if (date($format, strtotime($date)) == \'1970-01-01\' && $falseReturnNow && DateTime::createFromFormat(\'Y-m-d G:i:s\', $date) === FALSE) {
            return date($format);
        }
        return date($format, strtotime($date));
    }
}
原文链接:https://juejin.cn/post/6922619062187098126

分类:

技术点:

相关文章:

  • 2022-02-17
  • 2021-06-21
  • 2021-06-25
  • 2021-06-09
  • 2022-12-23
猜你喜欢
  • 2021-11-28
  • 2021-08-04
  • 2021-10-17
  • 2022-12-23
  • 2022-03-08
  • 2021-11-30
相关资源
相似解决方案