-2

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?

Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

3 Answers3

2

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"
arkascha
  • 41,620
  • 7
  • 58
  • 90
1

Here we are using DateTime and DateInterval for achieving desired output.

Try this code snippet here

<?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

Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
0

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)))
?>
Ashu
  • 1,320
  • 2
  • 10
  • 24
  • Thank you for this code snippet, which may provide some immediate help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its educational value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight May 10 '17 at 12:17