How to get next time occurrence from now, submitted in php?

I have an input file with type time. what I want to do is to get time from the moment now that is if time right now is 2019-11-26 23:50:00 and the value of input field if 22:30:00, I should get a date 2019-11-27 22:30:00.

How can achieve this in PHP? in short, get the datetime stamp for the next occurrence of 22:30:00 which is 2019-11-27 22:30:00 as per the given example.

answer found but can we optimize the code more ?

$a = explode(':', date('H:i:s', strtotime($validateData['time'])));
        $str = '+'.$a[0].' hours '.$a[1].' minutes '.$a[2].' seconds';
        $trigger_at = date(date('Y-m-d H:i:s', strtotime( $str, strtotime($validateData['date']))));
        return $trigger_at;

2 Answers

This is simpler and a lot more readable

$time = "21:30:00"; // Time from input
$today = date("Y-m-d $time");
$tomorrow = date("Y-m-d H:i:s", strtotime($today)+86400);
$date = strtotime($today) < strtotime("now") ? $tomorrow : $today;

Explanation: We take timestamp at specified hour for today and tomorrow, if today timestamp has been passed, we use tomorrow timestamp. Simple. 🙂

All you are doing is appending (concatenating) a string onto another string.

$time = "22:30:00"; // This is the time you have
$date = date("Y-m-d"); // Right now in yyyy-mm-dd format.
$newdatetime = $date.' '.$time;

That will give you the current date with the supplied time appended to it. You can convert that back into a timestamp using:

$timestamp = strtotime($newdatetime);

The answer below is based on the original question in which the time was assumed to be an offset from now. It is left here simply to avoid deleting a lot of code.

The function strtotime is easy to use for that. However, it doesn’t accept HH:MM:SS format. So, you have to alter the string. I would do it like:

$time = "22:30:00"; // This is the time you have
$a = explode(':', $time);
$str = '+'.$a[0].' hours '.$a[1].' minutes '.$a[2].' seconds'; // This breaks it into separate numbers with labels.
$date = date("Y-m-d h:i:s", strtotime($str)); // The adjusted date

You can change the format of the output as you like by changing the first string used in the date function.

Archive from:

Leave a Reply

Your email address will not be published. Required fields are marked *