Convert the FULL Excel date serial format to Unix timestamp

前端 未结 4 1392
南笙
南笙 2020-11-29 06:08

I\'ve seen lots of references to converting the \"date\" portion of the Excel serial date format, but everyone seems to skip the \"time\" portion of it.

Here is what

4条回答
  •  情歌与酒
    2020-11-29 06:46

    You clearly haven't looked very hard:

    Taken directly from the PHPExcel Date handling code:

    public static function ExcelToPHP($dateValue = 0) {
        if (self::$ExcelBaseDate == self::CALENDAR_WINDOWS_1900) {
            $myExcelBaseDate = 25569;
            //    Adjust for the spurious 29-Feb-1900 (Day 60)
            if ($dateValue < 60) {
                --$myExcelBaseDate;
            }
        } else {
            $myExcelBaseDate = 24107;
        }
    
        // Perform conversion
        if ($dateValue >= 1) {
            $utcDays = $dateValue - $myExcelBaseDate;
            $returnValue = round($utcDays * 86400);
            if (($returnValue <= PHP_INT_MAX) && ($returnValue >= -PHP_INT_MAX)) {
                $returnValue = (integer) $returnValue;
            }
        } else {
            $hours = round($dateValue * 24);
            $mins = round($dateValue * 1440) - round($hours * 60);
            $secs = round($dateValue * 86400) - round($hours * 3600) - round($mins * 60);
            $returnValue = (integer) gmmktime($hours, $mins, $secs);
        }
    
        // Return
        return $returnValue;
    }    //    function ExcelToPHP()
    

    Set self::$ExcelBaseDate == self::CALENDAR_WINDOWS_1900 as necessary to indicate the Excel base calendar that you're using: Windows 1900 or Mac 1904

    and if you want a PHP DateTime object instead:

    public static function ExcelToPHPObject($dateValue = 0) {
        $dateTime = self::ExcelToPHP($dateValue);
        $days = floor($dateTime / 86400);
        $time = round((($dateTime / 86400) - $days) * 86400);
        $hours = round($time / 3600);
        $minutes = round($time / 60) - ($hours * 60);
        $seconds = round($time) - ($hours * 3600) - ($minutes * 60);
    
        $dateObj = date_create('1-Jan-1970+'.$days.' days');
        $dateObj->setTime($hours,$minutes,$seconds);
    
        return $dateObj;
    }    //    function ExcelToPHPObject()
    

提交回复
热议问题