简体   繁体   中英

Comparing dates php/phpExcel

I get a date value from an excel file and I change it to date like this

$dateEx = $sheet->getCellByColumnAndRow(2,$line)->getValue();      
$date = date('Ymd',($dateEx - 25569)*24*60*60);

And I have 2 another date time that I convert from String to date

  $dateOuverture = '20150306';
  $dateFerm = '20150906';              

  $dateOuverture = new Datetime($dateOuverture);
  $dateOuverture = $dateOuverture->format('Ymd'); 


  $dateFerm = new Datetime($dateFerm);
  $dateFerm = $dateFerm->format('Ymd'); 

and when I want to compare the date with an if it doesnt works

if($date<=$dateFerm && $date>=$dateOuverture){
     echo "Im in the if";

}

what did I wrong?

Thanks for help

from excel I get numbers like this 42164.536761227 instead of dates

Those numbers are MS Excel serialized timestamp values

This is why PHPExcel provides functions to convert between MS Excel serialized timestamp values and PHP DateTime objects or Unix timestamps (and vice versa)

$dateTimeObject = PHPExcel_Shared_Date::ExcelToPHP(42164.536761227);
echo $dateTimeObject->format('Y-m-d H:i:s');

or

$unixTimestamp = PHPExcel_Shared_Date::ExcelToPHP(42164.536761227);
echo date('Y-m-d H:i:s', $unixTimestamp);

You can then use standard PHP functions to do any comparisons

PHP date functions accepts a timestamp as second argument, no ISO8601 date format. Strtotime does accept that, and returns a valid timestamp. Combine the two like this:

$dateEx = $sheet->getCellByColumnAndRow(2,$line)->getValue();
$iso8601Date = ($dateEx - 25569)*24*60*60;    
$date = new DateTime($iso8601Date);

See this link for more about date formats

Compare the DateTime objects

$dateOuverture = '20150306';
$dateFerm = '20150906';

$dateOuverture = new Datetime($dateOuverture);
$dateFerm = new Datetime($dateFerm);

if($date<=$dateFerm && $date>=$dateOuverture){
    echo "Im in the if";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM