Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 725
What have you tried Avatar asked Feb 26 '14 23:02

What have you tried


1 Answers

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

like image 121
hek2mgl Avatar answered Sep 25 '22 01:09

hek2mgl