Eoghan
Eoghan

Reputation: 1761

Getting seconds until the start of the next hour?

I'm writing a small API call which returns the current amount of seconds left until the end of the hour, the end of the day, and the end of the week.

Getting the end of day/week was easy, in just using strtotime('tomorrow') or strtotime('next sunday') and subtracting with time(). However, I'm not seeing any available function that would allow me to get the timestamp of the start of the next hour.

strtime('next hour') just returns back the current timestamp +1 hour - rather than the time remaining until the next hour starts.

Is there any simple way of accomplishing this?

Upvotes: 1

Views: 1724

Answers (2)

Funk Doc
Funk Doc

Reputation: 1643

If you really want to use strtotime you can do this

 $start=date("H:i:s");
 $end=date("H:00:00",strtotime("$start +1 hour"));
 $secondsleft = (strtotime($end) - strtotime($start));

Upvotes: 4

ceejayoz
ceejayoz

Reputation: 180126

I'd encourage you to consider the Carbon date library for this sort of math. It makes things quite trivial:

Carbon\Carbon::now()->endOfHour()->diffInSeconds(Carbon\Carbon::now())
Carbon\Carbon::now()->endOfDay()->diffInSeconds(Carbon\Carbon::now())
Carbon\Carbon::now()->endOfWeek()->diffInSeconds(Carbon\Carbon::now())

Upvotes: 4

Related Questions