2010-06-27 210 views
1

如果unix時間戳是從當前日期起21天到49天之間,我必須嘗試一下。任何人都可以幫我解決這個問題嗎?謝謝!unix時間戳之間的時差

+0

從當前日期的哪個方向開始21到49天?過去還是未來? – 2010-06-27 18:27:52

+0

對不起,忘了提及那個關鍵的細節!在過去 – pauld78 2010-06-27 18:32:11

回答

5

歡迎來到SO
這應做到:

if (($timestamp > time() + 1814400) && ($timestamp < time() + 4233600)) { 
// date is between 21 and 49 days in the FUTURE 
} 

這可以簡化,但我想你想看到一個更詳細的例子:)

我從21*24*60*601814400423360041*24*60*60

編輯:我假設未來日期。另請注意time()返回(而不是毫秒)自PHP中的Epoch以來。

這是你如何做到這一點的過去(因爲你修改你的問題):

if (($timestamp > time() - 4233600) && ($timestamp < time() - 1814400)) { 
// date is between 21 and 49 days in the PAST 
} 
+0

謝謝大衛,完美!這是過去21至49天,所以我只是修改你的片段 – pauld78 2010-06-27 18:34:28

+0

是的,我也修正了它:p – 2010-06-27 18:35:50

+0

請注意,由於夏令時等原因,有些日子比24小時更短/更長,計算不穩定。我通常避免對這種原始時間戳進行計算,而是使用內置函數進行日期操作。 – 2010-06-27 21:27:24

3

的PHP5 DateTime類非常適合這些類型的任務。

$current = new DateTime(); 
$comparator = new DateTime($unixTimestamp); 
$boundary1 = new DateTime(); 
$boundary2 = new DateTime(); 

$boundary1->modify('-49 day'); // 49 days in the past 
$boundary2->modify('-21 day'); // 21 days in the past 

if ($comparator > $boundary1 && $comparator < $boundary2) { 
    // given timestamp is between 49 and 21 days from now 
} 
+0

對象矯枉過正> _ < – 2010-06-27 18:41:03

3

strtotime在這些情況下非常有用,因爲您幾乎可以說出自然的英語。

$ts; // timestamp to check 
$d21 = strtotime('-21 days'); 
$d49 = strtotime('-49 days'); 

if ($d21 > $ts && $ts > $d49) { 
    echo "Your timestamp ", $ts, " is between 21 and 49 days from now."; 
} 
+1

儘管在這個例子中它可能是微不足道的,PHP 5.2.13源代碼中的time()函數是一行C代碼,而strtotime()函數大約是55行,並且調用了很多外部代碼。如果特別在循環中使用它,則time()將是要走的路。 – TomWilsonFL 2010-06-27 19:23:58

+0

的確如此。但是,如果您只需要設置一次時間戳,那麼考慮提高可讀性時,它不會太昂貴。 – 2010-06-27 19:37:40

+0

+1使用內置函數來說明與語言環境相關的日期問題。 – 2010-06-27 21:28:55