如何仅调用date()一次,然后以不同格式显示多次
问题描述:
我有一个页面,我用作由树莓派驱动的数字标志。该页面显示日期和时间以及显示当前天气。如何仅调用date()一次,然后以不同格式显示多次
我打电话date()
函数三个不同的时间。一种是确定天气图标是白天还是晚上,另一种是以较大数字显示时间,最后是显示当前日期。
有没有一种方法可以将date()
存储在一个变量中,然后以三种不同的方式使用它?
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
//header("Refresh: $sec; url=$page");
$bg = array(); // create an empty array
$directory = "images/"; //the directory all the images are in
$images = glob($directory . "*.jpg"); //grab all of the images out of the directory with .jpg extention
foreach($images as $image)
{
$bg[] = $image;//populate the empty array with an array of all images in the directory folder
}
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
$json_string="http://api.openweathermap.org/data/2.5/weather?lat=49.1985&lon=-113.302&appid=b29961db19171a5d4876c08caea9af0d&units=metric";
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
$now = date('U'); //get current time
$temp = round($obj['main']['temp']);
if($now > $obj['sys']['sunrise'] and $now < $obj['sys']['sunset']){
$suffix = '-d';
}else{
$suffix = '-n';
}
?>
<div id="todaysdatetime">
<div id="todaystime">
<span><?php echo(date("g:i A"));?></span>
</div>
<div id="todaysdate">
<span><?php echo(date("l\, F j<\s\up>S</\s\up>"));echo ' <i class="owf owf-', $obj['weather'][0]['id'].$suffix, '"></i> ', $temp, '°C'; ?></span>
</div>
</div>
答
你不能真正做到这一点,因为你传递给date()
什么是你想要在显示它的格式。date()
是你为了格式化日期调用该函数。
因此,您不能存储结果并再次使用它,因为结果是难以翻译回内部日期表示的人类可读字符串。你正在做的事情已经是最简单的(也是唯一的)做法,并且对你的表现影响也很小。
答
有两种方法。
- 获取带有
time()
的时间戳将它存储在变量和调用日期('YOUR_FORMAT',$ timestamp); - 使用类\DateTime和使用datetime对象的方法
format()
这两个选项有这个优势DATETIME将始终是相同的,因为代码的执行速度慢的也不会改变。
在您实际执行HTTP请求的同时,三个date()调用不会显着减慢您的代码。不要猜测为什么你的代码很慢,要进行基准测试。 – CodeCaster
基准与否,几个日期通话可以减缓任何明显数量的想法简直是荒谬可笑... – CBroe
@CBroe很高兴知道。我只是猜测在这一点上,为什么它可能会比在我的电脑上更慢。 – ShemSeger