2012-06-23 8 views
10

Ho visto molti riferimenti per convertire la parte "data" del formato di data seriale Excel, ma tutti sembrano ignorare la parte "tempo" di esso.Convertire il formato seriale di data FULL Excel in Unix timestamp

Ecco quello che devo fare:

Ho un file di Excel sto importazione. PHP in uso.

Sto incontrando il formato seriale Data Excel (dddddd.tttttt) e ho bisogno di convertirlo in un intero timestamp Unix.

Ho provato un paio di cose diverse, ma mi sto bloccando su come farlo in un movimento fluido.

+0

cosa ti dà lo strtotime()? – arijeet

+0

strtotime è __not__ per aiutare con n valore seriale excel, che è il numero di giorni dal 1/1/1900 (o forse 1/1/1904 a seconda che usi il calendario di Windows 1900 o Mac 1904) –

risposta

6

chiaramente non hanno guardato molto difficile:

tratte direttamente dai codice di gestione Data PHPExcel:

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 se necessario per indicare il calendario di base di Excel che si sta utilizzando: Windows 1900 o Mac 1904

e se si desidera un oggetto PHP DateTime invece:

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() 
+0

grazie a Mark. Tieni presente che potrei non avere la profondità dell'esperienza, anche se per la maggior parte sono in grado di trovare le cose. In questo caso, mentre sto analizzando il mio foglio elettronico, chiamo la funzione e le passo il valore della cella? – timebinder

+0

Come stai effettivamente leggendo la cartella di lavoro di Excel, in primo luogo? –

+0

apre con PHPExcel, iterando su ogni riga, ottenendo ogni valore di cella, quindi nel caso della colonna A, che ha il valore di data, sto fondamentalmente facendo $ cell = $ sheet-> getCell ('A'. $ RowIndex) , quindi $ array_data [$ rowIndex] ['A'] = $ cell-> getValue(); Da lì voglio solo impostarlo su una variabile già in formato timestamp Unix – timebinder

28

Si prega di utilizzare questa formula per passare da Excel data a data Unix, quindi è possibile utilizzare "gmdate" per ottenere la data reale in PHP:

UNIX_DATE = (EXCEL_DATE - 25569) * 86400 

e convertire da data di Unix ad oggi Excel, utilizzare questo formula:

EXCEL_DATE = 25569 + (UNIX_DATE/86400) 

Dopo aver fatto questa formula in una variabile, è possibile ottenere la data reale in PHP utilizzando questo esempio:

$UNIX_DATE = ($EXCEL_DATE - 25569) * 86400; 
echo gmdate("d-m-Y H:i:s", $UNIX_DATE); 

Grazie.

+1

Funziona come una funzione charm 'ExcelDateToUnix ($ dateValue = 0) { return ($ dateValue - 25569) * 86400; } ' – vonUbisch

+0

ancora una volta ... bella risposta ...;) – deemi

11

Questo oneliner ha funzionato per me, utilizzando PHPExcel, naturalmente.

$date_formated = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($date_int_val)); 
+0

funziona! grazie –

+0

PhpExcel è ora obsoleto. Il suo successore diretto PhpSpreadsheet ci consente di utilizzare il seguente metodo: '\ PhpOffice \ PhpSpreadsheet \ Shared \ Date :: excelToDateTimeObject ($ date_int_val)'. – Guicara

0

ho avuto lo stesso problema su un progetto, ero alla ricerca di un PHP Class to Read Excel as PHP Array. Sono stato fortunato che ho trovato 'SimpleXLSX' Class. È in grado di gestire i dati di Excel molto bene, ma ... ma ... ohh !! ma .... :( Ho capito che c'è qualche problema con il campo Date Reading From Excel. Nei valori di excel stava andando bene ma quando eravamo cercando di importarli, I valori di data diventano diversi. valuta alcune volte solo un numero e alcune volte un valore float. Eravamo alla ricerca di una soluzione '

perché sta accadendo, PERCHE PHP non ottenendo data corretta da Excel

' Poi, dopo i lotti di goggling abbiamo trovato il motivo:

@Source: reading xls date in php

Secondo il formato Excel 41397 è 2013-05-03 Excel memorizza le date e volte come un numero che rappresenta il numero di giorni dal 1900-Jan-0, più una parte frazionaria di un giorno di 24 ore: ddddd.tttttt. Questo è chiamato una data seriale, o data-ora seriale.

@Source: Excel date conversion using PHP Excel

Convert Excel Data Per Unix Data e poi convertire Unix Data di PHP Data

Così, ho fatto un po 'di classe helper per leggere di Excel Data per l'uso in PHP. Spero che aiuterà qualcuno e ridurrà gli sguardi e gli sforzi.

Ecco il mio codice di Read Excel as PHP Array() e Parse Excel Date as PHP Date

per principianti:

  1. Scarica SimpleXLSX.php dal dato esempio di codice
  2. convertito eccelle i dati (campo/valore) in array PHP (
  3. Convertire la data di Excel in PHP
  4. Ora .. Sì !! Excel dati sono pronti come un array PHP per muoversi in tabella di MySQL ...

Ecco Codice PHP:

<?php 
/* 
    EXCEL DATA EXAMPLE: 
    ---------------------------- 
    ID  Consumer_Date Delivery_Date Date_of_Dispatch Gift_Date_Created Active_Date    Approved_Date 
    536  -No-Data-  9-Nov-15  7-Nov-15   -No-Data-   10/31/2015 12:00:00 AM 4/11/2015 10:21 
    537  -No-Data-  -No-Data-  7-Nov-15   -No-Data-   10/23/2015 12:00:00 AM 3/11/2015 16:24 

*/ 

/* 
    EXCEL DATA IN PHP ARRAY FORMAT 
    ------------------------------- 
    Array 
    (
     [0] => Array 
      (
       [ID] => 536 
       [Consumer_Date] => -No-Data- 
       [Delivery_Date] => 42317 
       [Date_of_Dispatch] => 42315 
       [Gift_Date_Created] => -No-Data- 
       [Active_Date] => 10/31/2015 12:00:00 AM 
       [Approved_Date] => 42105.431574074 
     ) 
     [1] => Array 
      (
       [ID] => 537 
       [Consumer_Date] => -No-Data- 
       [Delivery_Date] => -No-Data- 
       [Date_of_Dispatch] => 42315 
       [Gift_Date_Created] => -No-Data- 
       [Active_Date] => 10/23/2015 12:00:00 AM 
       [Approved_Date] => 42074.683958333 
     ) 
) 

*/ 

/* ----------------- */ 
/* Excel_Date_Parser.php */ 
/* ----------------- */ 


// Numbers of days between January 1, 1900 and 1970 (including 19 leap years) 
define("MIN_DATES_DIFF", 25569); 

// Numbers of second in a day: 
define("SEC_IN_DAY", 86400); 

/** Set default timezone (will throw a notice otherwise) */ 
date_default_timezone_set('Asia/Kolkata'); 

/** 
* Class Excel_Date_Parser 
* 
* SetDateString($excel_date_value) : send excel date column value 
* GetDateString(): get your php date in Y-m-d format (MySQL) 
*/ 
class Excel_Date_Parser 
{ 

    /** 
    * Send Excel Date String Value Here 
    * @param [type] $date_from_excel [description] 
    * @return instance Excel_Date_Parser 
    */ 
    public function SetDateString($date_from_excel) { 
    $this->date_from_excel = $date_from_excel; 
    return $this; 
    } 

    /** 
    * Set Date Format Here, default is "Y-m-d" 
    * @param string $set_format_date [description] 
    */ 
    public function SetDateFormat($set_format_date = "Y-m-d") { 
    $this->set_format_date = $set_format_date; 
    } 

    /** 
    * Get what format is set 
    */ 
    public function GetDateFormat() { 
    return $this->set_format_date; 
    } 

    /** 
    * Return PHP date according to Set Format from Excel Date 
    * @return string php date 
    */ 
    public function GetDateString() { 

    // if value is valid date string 
    if (strtotime($this->date_from_excel)) { 

     /** 
     * Excel stores dates and times as a number representing the number of days since 1900-Jan-0, 
     * plus a fractional portion of a 24 hour day: ddddd.tttttt. 
     * This is called a serial date, or serial date-time. 
     * 
     * @source: https://stackoverflow.com/questions/17808750/reading-xls-date-in-php 
     */ 
     if (is_float($this->date_from_excel)) { 

     // date format 2015-25-12 
     $this->SetDateFormat("Y-d-m"); 
     $this->date_from_excel = date($this->GetDateFormat() , (mktime(0, 0, -1, 1, $this->date_from_excel, 1900))); 
     } 
     else { 

     // date format 2015-12-25 
     $this->SetDateFormat(); 

     // return converted date string in php format date format 2015-12-25 
     $this->date_from_excel = date($this->GetDateFormat() , strtotime($this->date_from_excel)); 
     } 
    } 

    /** 
    * Excel stores dates and times as a number representing the number of days since 1900-Jan-0, 
    * plus a fractional portion of a 24 hour day: ddddd.tttttt . 
    * This is called a serial date, or serial date-time. 
    * 
    * According to excel format 41397 is 2013-05-03 
    * @source: https://stackoverflow.com/questions/17808750/reading-xls-date-in-php 
    */ 
    else if (is_integer($this->date_from_excel)) { 
     $this->SetDateFormat(); 
     $this->date_from_excel = gmdate($this->GetDateFormat() , (($this->date_from_excel - MIN_DATES_DIFF) * SEC_IN_DAY)); 
    } 

    // return real value 
    else { 
     $this->date_from_excel = $this->date_from_excel; 
    } 

    // return date 
    return $this->date_from_excel; 
    } 
} 


/* ----------------- */ 
/* Excel_Reader.php */ 
/* ----------------- */ 

/* Show errors */ 
error_reporting(1); 

/* display error */ 
ini_set('display_errors', 1); 

/** 
* Using class SimpleXLSX 
* 
* Big Thanks!!!! to Sergey Shuchkin, Who made Excel Reader Class 
* 
* This class can be used to parse and retrieve data from Excel XLS spreadsheet files. 
* It can parse a given Excel XLS file by extracting its contents files and parsing the 
* contained XML spreadsheet file. 
* 
* The class provides functions to retrieve data for the spreadsheet worksheets, rows and cells. 
* 
* @link: http://www.phpclasses.org/package/6279-PHP-Parse-and-retrieve-data-from-Excel-XLS-files.html 
* @author: Sergey Shuchkin 
* @download: http://www.phpclasses.org/browse/download/zip/package/6279/name/simple-xlsx-2013-10-13.zip 
*/ 
require_once 'SimpleXLSX.php'; 


/* Adding my class Excel_Date_Parser */ 
require_once 'Excel_Date_Parser.php'; 


/** 
* [toPhpDate description] 
* @param [type] $array [description] 
*/ 
function toPhpDate($array) { 

    // create class object 
    $ed = new Excel_Date_Parser(); 

    // parse array and set 
    $array['Consumer_Date'] = $ed->SetDateString($array['Consumer_Date'])->GetDateString(); 
    $array['Delivery_Date'] = $ed->SetDateString($array['Delivery_Date'])->GetDateString(); 
    $array['Date_of_Dispatch'] = $ed->SetDateString($array['Date_of_Dispatch'])->GetDateString(); 
    $array['Gift_Date_Created'] = $ed->SetDateString($array['Gift_Date_Created'])->GetDateString(); 
    $array['Active_Date'] = $ed->SetDateString($array['Active_Date'])->GetDateString(); 
    $array['Approved_Date'] = $ed->SetDateString($array['Approved_Date'])->GetDateString(); 

    // return php array 
    return $array; 
} 

// make xls object 
$xlsx = new SimpleXLSX('Sony_RedemptionFormat 8-Dec-15.xlsx'); 

// get excel data as array 
$Excel_Array_Data = $xlsx->rows(); 

// Get Column Name 
$Excel_Column = $Excel_Array_Data[0]; 

// Remove Column Name From Array 
unset($Excel_Array_Data[0]); 

// Rest Data is Excel Data without Column 
$Excel_Data = $Excel_Array_Data; 

// Combine array for inserting in database 
foreach ($Excel_Array_Data as $key => $Excel_Data) { 
    $insert_data[] = array_combine($Excel_Column, $Excel_Data); 
} 

// show array data 
echo "<pre>", print_r($insert_data, true); 

// update array excel date 
$insert_data = array_map('toPhpDate', $insert_data); 

// show array data after update date 
echo "<pre>", print_r($insert_data, true); 

Spero che questo codice aiutare qualcuno. Stavo lottando per lo stesso problema, quindi ho creato questa piccola sceneggiatura per risparmiare tempo agli altri.

Happy PHPING !!!! :)

+0

L'utente sta chiedendo una soluzione utilizzando PHPExcel. L'installazione di una nuova libreria non è una soluzione. –

Problemi correlati