How to get seconds elapsed since midnight

Viewed 27166

Using PHP how do you get the number of seconds elapsed since midnight of the current day?

All i've tried right now is:

$hour=substr(date("h:i:s"),0,2);
$minute=substr(date("h:i:s"),3,2);
echo $hour."\r\n";
echo $minute."\r\n";

...but it doesn't return the correct server time of the response and I don't know how to do that.

10 Answers

In Carbon, the number of seconds elapsed since midnight can be found like this:

$seconds_since_midnight = $dt->secondsSinceMidnight();

And though there's no minutes since midnight I suppose you do:

$minutes_since_midnight = (int) floor($dt->secondsSinceMidnight()/60);

I'm keeping the rule that operations on numbers are always faster than operations on strings. When the numbers are integers, operations are even faster (because CPU registers are always "integer wide", means have 32-bit or 64-bit and all other non-floating point types are converted to integer before any operation is performed).

Anyway, I found such solution to count seconds till midnight with timezone include:

$tillmidnight = 86400 - (time() - mktime(0, 0, 0));

You wanted to get seconds elapsed since midnight so:

$sincemidnight = time() - mktime(0, 0, 0);

It is good to review your php.ini also and set your time zone (date.timezone under [Date] section) there. If you do not have access to php.ini, you can set your time zone in PHP code using date_default_timezone_set(); function.

Related