php 将天数添加到特定日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1923832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding days to specific day
提问by jsk
Many examples are about adding days to this day. But how to do it, if I have different starding day?
许多例子都是关于增加天数到今天。但是,如果我有不同的起始日,该怎么办?
For example (Does not work):
例如(不起作用):
$day='2010-01-23';
// add 7 days to the date above
$NewDate= Date('$day', strtotime("+7 days"));
echo $NewDate;
Example above does not work. How should I change the starding day by putting something else in the place of Date?
上面的例子不起作用。我应该如何通过在 Date 位置放置其他东西来更改起始日?
回答by Corey Ballou
For a very basic fix based on your code:
对于基于您的代码的非常基本的修复:
$day='2010-01-23';
// add 7 days to the date above
$NewDate = date('Y-m-d', strtotime($day . " +7 days"));
echo $NewDate;
If you are using PHP 5.3+, you can use the new DateTime libs which are very handy:
如果您使用的是 PHP 5.3+,则可以使用非常方便的新 DateTime 库:
$day = '2010-01-23';
// add 7 days to the date above
$NewDate = new DateTime($day);
$NewDate->add(new DateInterval('P7D');
echo $NewDate->format('Y-m-d');
I've fully switched to using DateTimemyself now as it's very powerful. You can also specify the timezone easily when instantiating, i.e. new DateTime($time, new DateTimeZone('UTC')). You can use the methods add()and sub()for changing the date with DateInterval objects. Here's documentation:
我现在已经完全改用DateTime自己了,因为它非常强大。您还可以在实例化时轻松指定时区,即new DateTime($time, new DateTimeZone('UTC')). 您可以使用DateInterval 对象的方法add()和sub()更改日期。这是文档:
回答by antpaw
$NewDate = date('Y-m-d', strtotime('+7 days', strtotime($day)));
回答by JonH
From php.com binupillai2003
来自 php.com binupillai2003
<?php
/*
Add day/week/month to a particular date
@param1 yyyy-mm-dd
@param1 integer
by Binu V Pillai on 2009-12-17
*/
function addDate($date,$day)//add days
{
$sum = strtotime(date("Y-m-d", strtotime("$date")) . " +$day days");
$dateTo=date('Y-m-d',$sum);
return $dateTo;
}
?>

