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条回答
Explosion°爆炸
2楼-- · 2020-03-08 09:29

This should work.

echo time() - strtotime("today");

This will only show your servers timezone though.

查看更多
Root(大扎)
3楼-- · 2020-03-08 09:29

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);

查看更多
欢心
4楼-- · 2020-03-08 09:30

I think you want to get time from start of the day to current hours and seconds of the day, this can be done like this, you will still need to set your timezone time in place of 'Asia/Karachi'. This gets correct time since midnight in user's timezone instead of server's timezone time.

Here is working link: http://codepad.viper-7.com/ykJC2R

//Get current time timestamp
$time_now = time();

//Create DateTime class object
$date = new DateTime(); 

//Set timestamp to DateTime object
$date->setTimestamp( $time_now );

//Set timezone so that code don't get server's timezone midnight time
$date->setTimezone(new DateTimeZone('Asia/Karachi'));

//Print current time in user's timezone
echo $date->format('Y-m-d H:i') . "<br />";

//Get time stamp for midnight tonight
$date->modify('today midnight');
$midnight_time = $date->getTimestamp();

//Print midnight time in user's timezone
echo $date->format('Y-m-d H:i') . "<br />"; 

    //Now you will need to subtract midnight time from current time in user's timezone
$seconds_since_midnight = $time_now - $midnight_time;

//Print seconds since midnight in your timezone
echo $seconds_since_midnight;
查看更多
Explosion°爆炸
5楼-- · 2020-03-08 09:32

Simplest I believe would be dividing the current time (in seconds) by the number of seconds in a day (60*60*24) and taking the remainder:

(time() % 86400)
查看更多
登录 后发表回答