質問

In csv cell contain date in format 31-Mar-90. Now If that csv created on Windows + MS Excel 2007, my php scripts shows in same format ie: 31-Mar-90 but if same date format added in csv that created on some other platform then php shows like: 31 Mar 1990

script is

$row = 1;
if (($handle = fopen($filename, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { //Reading the file
       $num = count($data);    
       for ($c = 0; $c < $num; $c++) {
           $csvData[$row][$c] = $data[$c];
       }    
       $row++;
   }            
   fclose($handle);
}
var_debug($csvData);

and once I open & save csv (created in other platform) in Windows MS-Excel 2007, php outputs 31-Mar-90 which is my requirement.

Here is csv: enter image description here

役に立ちましたか?

解決

Don't ever trust the input, just transform the date to timestamp and then apply the format you wish:

$csvData[$row][$c] = date('d-M-Y', strtotime( $data[$c] ) );

Or if you don't like the transform, validate the input and throw an error if you don't like the date format.

Check http://www.php.net/manual/es/function.strtotime.php

UPDATE

I forgot to mention: beware of the strtotime transformation, it has its own rules:

PHP: Problem with strtotime

Strtotime() doesn't work with dd/mm/YYYY format

So, better validate always the input, and then, apply the time transform

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top