I'm trying to convert a string that enters in my program from a JSON
to a date
, so I can compare it to actual time.
I'm using strtotime()
but it converts the original date to 01/01/1970 12:00:00
.
Here's my code:
var_dump($requestOrder->date);
$requestDate= date('d/m/Y h:i:s', strtotime($requestOrder->date));
var_dump($requestDate);
Where, date
inside the $requestOrder
is equal to "24/12/2021 00:00:00"
.
And here's what I'm getting:
string(19) "24/12/2021 00:00:00"
string(19) "01/01/1970 12:00:00"
I need to convert it to a date
because, lately, in some point of my code, I do this:
if($requestDate< date('d/m/Y h:i:s', time())) {
...
}
I've been trying a lot of options to solve this problem, such as changing the /
to -
, using other formats for the date, etc, but with no luck. In the case of using a str_replace
to change the /
to -
, it works and doesn't show a 70's date, but then it doesn't do the comparison well, it always detects the date smallest to actual one.
Does someone see what I'm skipping?
CodePudding user response:
The date()
function returns a string not a DateTime object. It would be better to use the actual DateTime
class and its createFromFormat
function.
$requestDate = date_create_from_format('d/m/Y h:i:s', $requestOrder->date);
or object oriented style
$requestDate = DateTime::createFromFormat('d/m/Y h:i:s', $requestOrder->date);
https://www.php.net/manual/en/datetime.createfromformat.php
CodePudding user response:
Please check below code:
$requestOrder->date="24/12/2021 00:00:00";
$date=str_replace("/",'-',$requestOrder->date);
if(strtotime($date)>time())
{
//this will execute as request date is greater than current date
}
if(strtotime($date)<time())
{
//this will not execute as current date less than request date
}