简体   繁体   English

如何比较文本文件中的日期和今天的日期

[英]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 - 我的date.txt文件的内容-

2018,2,18 (this is line 1) 2018,2,18(这是第1行)

Test (This is line 2 in my file) 测试(这是我文件的第2行)

I want to compare 2018,2,18, line 1 in the file, with the current date. 我想将文件中的2018、2、18,第1行与当前日期进行比较。 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? 是因为第1行虽然会返回日期,但实际上是数组还是不是日期?

Your strtotime($expire_date) is returning FALSE . 您的strtotime($expire_date)返回FALSE I have replaced comma with dash in your date string. 我在您的日期字符串中用破折号替换了逗号。 Also consider I'm using time() function which returns current Unix timestamp. 还要考虑我正在使用time()函数,该函数返回当前的Unix时间戳。 I have considered the date in your file is UTC date. 我认为您文件中的日期为UTC日期。

$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';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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