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.
The shortest solution would probably be this:
The reason this works is that
strtotime
uses the second parameter to determine the date part of the time string. In this case, I'm using0
, which means the full string results in1970-01-01 12:34:56 UTC
.strtotime
then returns the UNIX timestamp (the number of seconds elapsed since1970-01-01 00:00:00 UTC
). Note: the first parameter hasUTC
appended to prevent the time being interpreted as local.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.
Multiply the current hour by the number of seconds in each hour and add it to the number of minutes multiplied by the number of seconds in each minute.
Based on your comment, if you are receiving the time as a string and want to calculate the number of seconds from that time:
There you go. Read into time() function of PHP and strtotime().
If you are using DateTime: