Mary Mary - 5 months ago 23
PHP Question

subracting minutes and seconds in php datetime

I have this datetime code below. I want to subtract 23 hours and 59 minutes in $begin variable:

$date = 2016-03-14 23:59:59;
$given = new DateTime($date, new DateTimeZone("Asia/Tokyo"));
$given->setTimezone(new DateTimeZone("UTC"));
$end = $given->format("Y-m-d H:i:s");
$begin = date('Y-m-d H:i:s',strtotime('-23 hours',strtotime($end)));


Now The output is:

$end is: 2016-03-14 14:59:59
$begin is: 2016-03-13 15:59:59


The output I want is:

$end is: 2016-03-14 14:59:59
$begin is: 2016-03-13 15:00:00


How can I subtract the minutes in seconds in begin? Or there is a best way to do it?

Answer

As you just want to change the hour, you can make this to get the desire result, but you also can do something else like Amit Roy did or ceejayoz suggest. This is a pretty simple solution, just do it: reset the min and sec to 00 so that your output shows like you want.

echo $begin = date('Y-m-d H:00:00',strtotime('-23 hours', strtotime($end)));
Comments