如何只调用一次date(),然后以不同的格式多次显示

时间:2017-10-18 20:21:29

标签: php date variables

我有一个页面,我用作树莓派驱动的数字标牌。该页面显示日期和时间,并显示当前天气。

我分三次调用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 ' &nbsp;&nbsp; <i class="owf owf-', $obj['weather'][0]['id'].$suffix, '"></i> ', $temp, '&deg;C'; ?></span>
    </div>

</div>

2 个答案:

答案 0 :(得分:1)

您无法真正做到这一点,因为您传递给date()的内容是您想要显示的格式。date()是您为了格式化日期而调用的函数。

因此,您无法存储结果并再次使用它,因为结果是一个人类可读的字符串,很难转换回内部日期表示。您正在做的事情已经是最简单(也是实际,唯一)的方式,而且对您的表现的影响也很小。

答案 1 :(得分:1)

有两种方法。

  1. 获取时间戳,time()将其存储在变量和通话日期(&#39; YOUR_FORMAT&#39;,$ timestamp);
  2. 使用课程\DateTime并在日期时间对象上使用方法format()
  3. 这两个选项具有以下优势:datetime将始终相同,并且由于代码执行缓慢而无法更改。