简体   繁体   中英

How can I compare the date from text file to today's date

<?php
$myFile = strtolower('date.txt');
$lines = file($myFile);     
$expire_date = $lines[0];



$date = strtotime($expire_date);
//$date->format("y,m,d");
$now = new DateTime();
$now->format("y,m,d");

if($now < $date) {
    echo 'Have not reached date yet.';
}else{
echo 'Date in file is old';
}
?>

Content of my date.txt file -

2018,2,18 (this is line 1)

Test (This is line 2 in my file)

I want to compare 2018,2,18, line 1 in the file, with the current date. Code keeps saying that the date is old when it's clearly in the future. Is it because line 1, although will return the date, is actually an array or not a date?

Your strtotime($expire_date) is returning FALSE . I have replaced comma with dash in your date string. Also consider I'm using time() function which returns current Unix timestamp. I have considered the date in your file is UTC date.

$myFile = strtolower('date.txt');
$lines = file($myFile);     
$date = $lines[0];
$date = str_replace(',', '-', $date);
$date = strtotime($date);

if(time() < $date) {
    echo 'Have not reached date yet.';
}else{
    echo 'Date in file is old';
}

Or you can also create your date from the format in file:

$myFile = strtolower('date.txt');
$lines = file($myFile);     
$date = $lines[0];
$date = date_create_from_format('Y,m,d', $date);
$date = date_format($date, 'Y-m-d');
$date = strtotime($date);

if(time() < $date) {
    echo 'Have not reached date yet.';
}else{
    echo 'Date in file is old';
}

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