node_man
node_man

Reputation: 1449

subtract 2 days from a date which is in m-d-Y H:i:s format in PHP

I get the current date using this code :

$currentdate= date('m-d-Y H:i:s');

echo $currentdate; // prints 06-22-2019 11:02:49

To subtract two days from the current date I use this code :

 $date = date('m-d-Y H:i:s ', strtotime('-2 days', strtotime($currentdate)));
 echo $date; // print's 12-30-1969 01:00:00       

The expected output is 06-20-2019 11:02:49 //basic requirement is just that the date should be current date - 2 days. What I'm I doing wrong here? This code works perfectly if the dates are in Y-m-d H:i:s format.

Upvotes: 1

Views: 4124

Answers (3)

Nitesh Garg
Nitesh Garg

Reputation: 179

$currentdate= date('m-d-Y H:i:s');
echo $currentdate; //gives 06-22-2019 14:58:55


$date = date('m-d-Y H:i:s ', strtotime('-2 days', strtotime(date('Y-m-d H:i:s'))));
echo $date;  //gives 06-20-2019 14:58:55

Upvotes: 2

Niklesh Raut
Niklesh Raut

Reputation: 34914

Check php datetime format there is no m "-" d "-" y format.

enter image description here

But you can Use M "-" d "-" y or M "-" d "-" Y

Check live Example

Check More on Official Link

Upvotes: 1

node_man
node_man

Reputation: 1449

So as per the suggestions from the comments on this question I was able to get the output using this code by replacing - with / :

$currentdate= date('m/d/Y H:i:s'); //prints 06/22/2019 11:26:05
$date = date('m/d/Y H:i:s ', strtotime('-2 days', strtotime($currentdate)));
echo str_replace('/', '-', $date);   //prints 06-20-2019 11:20:50 which is the desired output

Upvotes: 0

Related Questions