Reputation: 763
I am learning to use PHP DateTime class and I came across the handy 'setDate' method. I tried to do the following to compare 2 dates:
$date = new DateTime();
$newDate = clone $date;
$newDate->setDate(2017, 08, 29);
if($date > $newDate){
echo 'yes';
} else{
echo "no";
}
According to the current date it shall return 'no' but it returned 'yes'. so I did a var_dump($newDate);
and it returned:
object(DateTime)[2]
public 'date' => string '2016-12-29 00:31:02.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'Europe/Zurich' (length=13)
It returned 2016-12-29 as the date which is not what I intended to set.
surely there something really wrong with what I am doing. Please help me find my mistake. Thanks
Upvotes: 1
Views: 815
Reputation: 2194
There is no need for the clone - just instantiate the new DateTime object according to your needs. Example: https://iconoun.com/demo/temp_sameer.php
<?php // demo/temp_sameer.php
/**
* Working with DateTime objects
*
* https://stackoverflow.com/questions/45426371/php-setdate-function-of-datetime-setting-different-date
* http://php.net/manual/en/datetime.construct.php
*/
error_reporting(E_ALL);
echo '<pre>';
// NOW
$date = new DateTime();
// DIFFERENT DATE
$newDate = new DateTime('2017-08-29');
// SHOW THE OBJECTS
var_dump($date, $newDate);
// MAKE THE COMPARISONS
if($date > $newDate){
echo 'yes';
} else{
echo "no"; // OUTPUTS "no"
}
Upvotes: 0
Reputation: 72269
Instead of 08
, it need to be 8
like below:-
<?php
$date = new DateTime();
$newDate = clone $date;
$newDate->setDate(2017, 8, 29);
if($date > $newDate){
echo 'yes';
} else{
echo "no";
}
Output:-https://eval.in/839909
Why:- As @Mark Baker tell correctly:-
Numbers prefixed with 0
in PHP are treated as octal
, so 08
is octal 8
, which is an invalid octal number, so treated as 0
And because of it you get yes
as output:- https://eval.in/839910
You can check a number is octal or not like below:-
<?php
function is_octal($x) {
return decoct(octdec($x)) == $x;
}
echo is_octal(08); // true
Output:- https://eval.in/839915 (the above code will work in php<7)
Upvotes: 2