PHP strtotime returning always midnight
Asked Answered
N

4

12

I'm having a weird problem. When I do strtotime it's not considering the hours part of the original date, and it's always returning midnight. I tried to research but I couldn't find anything specific.

Is there something I'm missing?

$original_date = "2015-08-07 02:00:00";
$next_date = date('Y-m-d H:i:s', strtotime("monday this Week +1 week", strtotime($original_date)));

It returns $next_date as 2015-08-14 00:00:00

Nonagenarian answered 21/8, 2015 at 4:29 Comment(1)
I'm not sure how to correct it, but giving strtotime a specific day like Monday sets it to Monday 00:00:00 and then the other calculations use that.Cykana
S
5

Try this, add time which you want to retrieve in next date,.

$original_date = "2015-08-07 02:00:00";
echo $next_date = date('Y-m-d H:i:s', strtotime("monday this Week 02:00:00 +1 week", strtotime($original_date)));
Sebrinasebum answered 21/8, 2015 at 4:46 Comment(3)
actually when saying monday this week, it will take date only and add 00:00:00 mid night internally, so we have just added time in the strtotime.Sebrinasebum
This works! Would you advice to always add the hour as a security blanket?Nonagenarian
@Nonagenarian yes you should always add it when you want to retain your hours, mins and secs.Sebrinasebum
C
3

monday this week +1 week assumes you’re looking for midnight of the monday of the week of the passed in time. If you want to preserve the hours part of the time, then you can append it to your date format because it should always be the same as in $original_date

date('Y-m-d ' . date('H:i:s', strtotime($original_date)), strtotime("monday this Week +1 week", strtotime($original_date)));
Cinematography answered 21/8, 2015 at 4:45 Comment(2)
Hi, it didn't work for me output was 2015-08-10 19:33:35. I modify to date('Y-m-d', strtotime("monday this Week +1 week", strtotime($original_date))).' '.date('H:i:s', strtotime($original_date)) and it worked.Nonagenarian
@Nonagenarian that works too, I was missing the strtotime callCinematography
C
3

When you use monday in strtotime you're resetting the time back to 00:00:00. You will have to explicitly pass the time in either your date or strtotime to get your desired behavior. See this same question for a similar issue.

$next_date = date('Y-m-d H:i:s', strtotime("monday this Week +1 week " . date('H:i:s', strtotime($original_date)), strtotime($original_date)))
Cartel answered 21/8, 2015 at 4:50 Comment(0)
B
3
$date = strtotime('2018-08-14 02:00:00');
$next_date = date('Y-m-d H:i:s', strtotime("monday this Week 02:00:00 +1 week", $date)); // 2018-08-20 02:00:00
Behold answered 21/8, 2015 at 4:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.