2010-04-09 97 views
10

我不知道如何正確解釋這個,但只是爲你們一些樣本,以便你真的可以得到我想說的。php得到未來的日期時間

今天是2010年4月9日

7從現在天是四月16,2010

進出口尋找一個PHP代碼,它可以給我確切的日期給人的天數間隔之前當前日期。

我一直在尋找一個線程,可以解決,甚至給如何解決這一個提示,但我什麼都沒有找到。

+0

難道這可能會被表述爲「我要加上' $ x'到特定日期的天數「? – deceze 2010-04-09 06:30:16

+0

你的問題不清楚。你能重新指定什麼是已知的參數和你感興趣的值? – 2010-04-09 06:35:18

回答

25

如果你正在使用PHP> = 5.2,我強烈建議你使用新DateTime對象,這使得與日期輕鬆了許多工作:

<?php 
$date = new DateTime("2006-12-12"); 
$date->modify("+7 day"); 
echo $date->format("Y-m-d"); 
?> 
+0

很好的回答,, 它幫助我很多 – 2010-04-09 07:38:58

+1

或1班輪'echo date_create(「2006-12-12」) - > modify(「+ 7 day」) - > format(「Y-m-d」); – 2016-06-20 11:54:11

9

看看這裏 - http://php.net/manual/en/function.strtotime.php

<?php 
// This is what you need for future date from now. 
echo date('Y-m-d H:i:s', strtotime("+7 day")); 

// This is what you need for future date from specific date. 
echo date('Y-m-d H:i:s', strtotime('01/01/2010 +7 day')); 
?> 
+0

+1。你可能不想'回聲strtotime(...)'。相反,使用日期函數中的返回值,如'echo date('Y-m-d H:i:s',strtotime(' - 7 days'))''。 – 2010-04-09 06:33:07

0

您可以使用mktime與日期。 (http://php.net/manual/en/function.date.php

日期爲您提供當前日期。這比簡單地添加/減去時間戳更好,因爲它可以考慮夏令時。

<?php 
# this gets you 7 days earlier than the current date 
$lastWeek = mktime(0, 0, 0, date("m") , date("d")-7, date("Y")); 
# now pretty-print it out (eg, prints April 2, 2010.) 
echo date("F j, Y.", $lastWeek), "\n"; 
?> 
2

您將不得不查看strtotime()。我想像你的最終代碼會是這個樣子:

$future_date = "April 16,2010"; 
$seconds = strtotime($future_date) - time(); 
$days = $seconds /(60 * 60* 24); 
echo $days; //Returns "6.0212962962963" 
+0

「6.0212962962963」 - PHP浮點精度問題的經典示例:) – 2010-04-09 06:42:53

+0

不是,只是_exact_天數表示爲小數。 – Sam152 2010-04-09 09:13:35

1

如果您使用PHP> = 5.3,這可能是一個選項。

<?php 
$date = new DateTime("2006-12-12"); 
$date->add(new DateInterval("P7D")); 
?> 
5

接受的答案是沒有錯,但不是最好的解決方案:

日期時間類需要在構造一個可選的字符串,它可以定義相同的邏輯作爲修改方法。

<?php 
$date = new DateTime("+7 day"); 

例如:

<?php 
namespace DateTimeExample; 

$now = new \DateTime("now"); 
$inOneWeek = new \DateTime("+7 day"); 

printf("Now it's the %s", $now->format('Y-m-d')); 
printf("In one week it's the %s", $inOneWeek->format('Y-m-d')); 

有關可用相對格式的列表(DateTime構造)看看http://php.net/manual/de/datetime.formats.relative.php