简体   繁体   中英

Php dates is not compare properly

I am new in PHP

when I am trying to do this

if( date('m-Y',strtotime('2016-11-01 00:00:00')) < date('m-Y') ) {
    echo "yes";
} else {
    echo 'no';
}

but it always do false [output 'no'].

I must need to compare months is less than current month , means compare date do not have same months

where I am wrong to compare that date ?

Use DateTime to compare dates:

$date = new DateTime('2016-11-01 00:00:00');
$now = new DateTime();

if ($date < $now && $date->format('m-Y') != $now->format('m-Y')) {
    echo 'yes';
} else {
    echo 'no';
}

I copied your program so that it reads:

<?php
$x=date('m-Y',strtotime('2016-11-01 00:00:00'));
echo "$x\n";
$y=date("m-Y");
echo "$y\n";

if ($x < date('m-Y') ) {
    echo "yes";
} else {
    echo 'no';
}

On running it the output is:

# php x.php 
11-2016
01-2017
no

That is why it fails. If you are checking for just the month you need to check for equality. Otherwise you need to reorder the date formatting to be "Ym" (not 'm-Y') for less/greater than comparisons. Comparing the strings is fine.

date function always return a string. In your if construct you compare two strings. For current time:

"11-2016" < "01-2017"

In this case "11-2016" greater than "01-2017" . It will be better to use DateTime class.

$date = new DateTime('2016-11-01 00:00:00');
$now = new DateTime();

if ($date < $now && $date->format('m-Y') != $now->format('m-Y')) {
    echo 'yes';
} else {
    echo 'no';
}

or in your example you need to change format to 'Y-m' .

You should use a decent format to compare the dates. Instead of mY , use Ymd .

Currently, you are converting the dates to strings, with their months first. So the first date becomes 11-2016 , the second becomes 01-2017 . PHP compares these as strings, and finds that 0 is less thans 1 , so considers the second string to be less.

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