2010-04-09 54 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