简体   繁体   中英

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 Ymd H:i:s format.

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

在此处输入图片说明

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

Check live Example

Check More on Official Link

$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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM