Adding days to specific day

自闭症网瘾萝莉.ら 提交于 2019-12-04 16:37:55

问题


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?


回答1:


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:

$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 DateTime myself 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:

  • http://php.net/manual/en/class.datetime.php
  • http://php.net/manual/en/class.dateinterval.php



回答2:


$NewDate = date('Y-m-d', strtotime('+7 days', strtotime($day)));



回答3:


From 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;
}

?> 


来源:https://stackoverflow.com/questions/1923832/adding-days-to-specific-day

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!