How to get seconds elapsed since midnight

2020-03-08 08:30发布

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.

标签: php
10条回答
家丑人穷心不美
2楼-- · 2020-03-08 09:07

The shortest solution would probably be this:

$time = "12:34:56";
echo strtotime("{$time}UTC", 0);

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 using 0, which means the full string results in 1970-01-01 12:34:56 UTC. strtotime then returns the UNIX timestamp (the number of seconds elapsed since 1970-01-01 00:00:00 UTC). Note: the first parameter has UTC appended to prevent the time being interpreted as local.

查看更多
走好不送
3楼-- · 2020-03-08 09:08
echo time() - strtotime('today');
查看更多
混吃等死
4楼-- · 2020-03-08 09:12

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.

查看更多
可以哭但决不认输i
5楼-- · 2020-03-08 09:17
echo (date('G') * 3600 + date('i') * 60);

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.

查看更多
ゆ 、 Hurt°
6楼-- · 2020-03-08 09:21

Based on your comment, if you are receiving the time as a string and want to calculate the number of seconds from that time:

$time = strtotime($_GET['time']); // Do some verification before this step
$midnight = strtotime("00:00"); // Midnight measured in seconds since Unix Epoch
$sinceMidnight = $time - $midnight; // Seconds since midnight

There you go. Read into time() function of PHP and strtotime().

查看更多
倾城 Initia
7楼-- · 2020-03-08 09:25

If you are using DateTime:

 $timeDiff = $time->diff(new \DateTime("today")); 
 $timeDiffSec = $timeDiff->h* 3600 + $timeDiff->i*60 + $timeDiff->s;
查看更多
登录 后发表回答