I have a date stored in a variable:
$date = '2017-06-01';
And I want to go one
day back. So in this case, the variable should end up being:
$date = '2017-05-31';
What's the appropriate way to go "one day back" in PHP?
I have a date stored in a variable:
$date = '2017-06-01';
And I want to go one
day back. So in this case, the variable should end up being:
$date = '2017-05-31';
What's the appropriate way to go "one day back" in PHP?
The documentation of PHPs DateTime
class gives a perfect example for what you ask. You just would have to read it...
<?php
$date = new DateTime('2017-06-01');
$date->sub(new DateInterval('P1D'));
var_dump($date->format('Y-m-d'));
The output obviously is:
string(10) "2017-05-31"
Here we are using DateTime and DateInterval for achieving desired output.
<?php
ini_set('display_errors', 1);
$noOfDays=1;//no of days to subtract
$date = '2017-06-01';
$dateTime= new DateTime($date);
$result=$dateTime->sub(new DateInterval("P".$noOfDays."D"));//subtracting date by $noOfDays days
print_r($result->format("Y-m-d"));//returning specific format of date.
Output:
2017-05-31
here strtotime('-1 day', strtotime($date) subtract 1 day from given date & the convert into date with date function with given format :
<?php
$date = '2017-06-01';
echo date('Y-m-d', strtotime('-1 day', strtotime($date)))
?>