2015-02-11 167 views
-1

我需要根據特定日期和時間在php頁面中顯示內容。我需要在有限的時間(在兩個定義的日期之間)顯示content1,在到期日期和時間之後顯示content3。 此外,我需要更改時區的可能性,所以時間應該由服務器提供。PHP:我如何根據時間和日期顯示內容?

我走到這一步,是這樣的:

<?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 } ?> 

的問題是,這個腳本只考慮日期,而不是時間。

+0

'2009' ??? ???無論如何,它比這更復雜。您需要時間來確定用戶的位置,而不是服務器的時間。 – HamZa 2015-02-11 10:35:01

+2

腳本只考慮日期而不考慮時間。可能是因爲你沒有使用時間。 – 2015-02-11 10:35:12

+0

@HamZa - 這要看。如果你只想要你當地的時區,這應該就足夠了。其他時區的用戶將能夠在其他時區之前/之後查看內容。 – AnotherGuy 2015-02-11 10:50:26

回答

2

您應該使用內置的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) 
+0

如果您提供沒有時間分量的日期字符串,則假定爲午夜(即00:00:00) – AcidReign 2015-02-11 10:53:08

+0

這很有效。解釋也很清楚。這比我預期的更簡單。 – user3161330 2015-02-12 09:44:32

0

我會擴展在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時間戳。

相關問題