PHP get next occurrence of Monday from a certain date (with time)
Asked Answered
F

1

6

I'm looking for the next Thursday after a specific date, say 2014-02-25. The problem I'm having here is that when I use the below code, the time seems to be erased.

<?php
    $timestamp = '2014-02-25 10:30:00';

    echo date('Y-m-d H:i:s', strtotime("next Thursday", strtotime($timestamp)));
?>

The result I am getting is 2014-02-27 00:00:00 when I would like it to be 2014-02-27 10:30:00

Is there something I am missing here that is causing the time to be set to midnight?

I appreciate the help, thanks.

Fry answered 26/2, 2014 at 23:38 Comment(7)
Does the next Thursday start at 10:30 or 00:00?Kinelski
@kingkero I honestly can't tell if that's sarcasm or not ... Have an idea for how to maintain the time on that?Fry
It is correct. Thursday starts at midnight.Metabolic
@Whathaveyoutried Say it is 26.02. 22:00, is the next Thursday now in 2 hours or 24?Kinelski
@kingkero Right, I understand the functionality now, thanks.Fry
@Whathaveyoutried: Say the timestamp says 10:30am but next Thursday means you have crossed into daylight savings time. Do you want the time of the result to be 10:30am (maintain wall clock time) or 11:30am (maintain absolute time)?Ardeb
@Ardeb For this question, maintaining clock time is fine. I can on my own time workout the DSTFry
D
9

There is no time format that can directly express this. You need to produce a format like

next Thursday 10:30:00

... manually and pass that to strtotime(). The time information you need to extract from the reference time string. Like this:

$refdate = '2014-02-25 10:30:00';
$timestamp = strtotime($refdate);

echo date('Y-m-d H:i:s',
    strtotime("next Thursday " . date('H:i:s', $timestamp), $timestamp)
);

The same results could be achieved using string concatenation:

echo date('Y-m-d', strtotime("next Thursday", $timestamp)
    . ' ' . date('H:i:s', $timestamp);

The documentation for so called relative time formats can be found here

Dunfermline answered 26/2, 2014 at 23:42 Comment(4)
Hey, thanks for the answer. Testing this, I'm getting the same response as my original code which is midnight on the 27th. The result I'm looking for is 10:30 on the 27th. Any chance of that happening?Fry
Ok, got it. :) .. Let me checkDunfermline
Beautiful, thank you .. could you point me towards some documentation for the above? I've been reading about strtotime all day and haven't come across the concatenation as done above in your answer. I'm referring to the way you concatenated the time to "Next thursday"Fry
Have added that. The term you are referring to is called relative time formatsDunfermline

© 2022 - 2024 — McMap. All rights reserved.