PHP:如何显示基于时间和日期的内容


PHP: how do I show contents based on time and date?

我需要在php页面中显示基于特定日期和时间的内容。我需要在某个日期之前显示content1,在有限的时间内显示content2(在两个定义的日期之间),在到期日期和时间之后显示content3。此外,我需要更改时区的可能性,所以时间应该由服务器提供。

到目前为止,我得到了以下信息:

<?php 
$exp_date = "2009-07-20";
$exp_date2 = "2009-07-27";
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
$expiration_date2 = strtotime($exp_date2);
if ($expiration_date > $today)
{ ?>
<!-- pre-promotion week content -->
<?php } else if ($expiration_date2 > $today) { ?>
<!-- promotion week content -->
<?php } else { ?>
<!-- expired/post-promotion week content -->
<?php } ?>

问题是这个脚本只考虑了日期而没有考虑时间。

您应该使用内置的DateTime对象:http://php.net/manual/en/book.datetime.php

您还应该设置时区:http://php.net/manual/en/function.date-default-timezone-set.php

date_default_timezone_set("America/New_York");

或者,您可以设置每个对象的时区:

$exp_date = new DateTime("2009-07-20", new DateTimeZone("America/Los_Angeles"));
$exp_date2 = new DateTime("2009-07-27", new DateTimeZone("America/Los_Angeles"));
$today = new DateTime();
if($today < $exp_date) {
   /*...*/
} elseif($today < $exp_date2) {
   /*...*/
} else {
   /*...*/
}

注意:我特意使用了两个不同的时区,以表明您可以将服务器放在一个时区,并使用其他时区的日期。例如:

$ny = new datetime('2015-02-11 05:55:00', new DateTimeZone('America/New_York'));
$la = new datetime('2015-02-11 02:55:00', new DateTimeZone('America/Los_Angeles'));
var_dump($ny == $la); // bool(true)

我会通过以下添加将date()函数中使用的格式扩展为包括小时、分钟甚至秒(如果您想要这样的精度)。

/*
 * Check the documentation for the date() function to view
 * available format configurations.
 *
 * H - hours 24 format
 * i - minutes with leading zero
 * s - seconds with leading zero
 */
$today = date('Y-m-d H:i:s');

当它与strtotime()函数一起使用时,您应该得到一个非常精确的UNIX时间戳。