Set time in php to 00:00:00

送分小仙女□ 提交于 2020-01-12 07:24:06

问题


I need to display the time but it must start from 00:00:00? I've got the following but it uses the current time.

print(date("H:i:s"));

回答1:


As an alternative to mktime(), try the newer DateTime class, eg

$dt = new DateTime;
$dt->setTime(0, 0);
echo $dt->format('H:i:s');

// Add one hour
$dt->add(new DateInterval('PT1H'));
echo $dt->format('H:i:s');

Update

The flexibility of DateInterval makes this a very good candidate for a timer, eg

// add 2 years, 1 day and 9 seconds
$dt->add(new DateInterval('P2Y1DT9S'));



回答2:


Use mktime() if you want to start with midnight for the current date:

<?php

echo date('l jS \of F Y h:i:s A',mktime(0,0,0));

?>

OUTPUTS

Friday 14th of October 2011 12:00:00 AM

http://codepad.org/s2NrVfRq

In mktime(), you pass arguments for hours, minutes, seconds, month, day, year, so set hours, minutes, seconds to 0 to get today at midnight. (Note, as Phil points out, mktime()'s arguments are optional and you can leave month, day, year out and it will default to the current date).

The mktime() function returns a unix timestamp representing the number of seconds since the unix epoch (January 1, 1970). You can count up from it in seconds or multiples of seconds.

<?php

// $midnight = mktime(0,0,0,date('m'),date('d'),date('Y'));
// The above is equivalent to below
$midnight = mktime(0,0,0);

echo date('l jS \of F Y h:i:s A',$midnight)."\n";
echo date('l jS \of F Y h:i:s A',$midnight+60)."\n"; // One minute
echo date('l jS \of F Y h:i:s A',$midnight+(60*60))."\n"; // One hour

?>

OUTPUTS

Friday 14th of October 2011 12:00:00 AM
Friday 14th of October 2011 12:01:00 AM
Friday 14th of October 2011 01:00:00 AM

http://codepad.org/FTr98z1n




回答3:


date() uses the current time when you don't pass in an explicit timestamp. See the optional argument in the date documentation.

If you want to explicitly format midnight, use:

date("H:i:s", mktime(0, 0, 0));



回答4:


try to use this syntax:

print(date("H:i:s", 0));

or

print(date("H:i:s", 10)); // 10 seconds


来源:https://stackoverflow.com/questions/7768716/set-time-in-php-to-000000

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!