假设我有一个以下格式的日期: 2010-12-11 (year-mon-day)
使用PHP,我想将日期增加一个月,如果需要的话,我希望年份自动增加(即从2012年12月增加到2013年1月)。
致以问候。
发布于 2010-05-20 08:45:42
$time = strtotime("2010.12.11");
$final = date("Y-m-d", strtotime("+1 month", $time));
// Finally you will have the date you're looking for.发布于 2014-06-03 19:55:14
我需要类似的功能,除了一个月的周期(加月减1天)。在搜索S.O.一段时间后,我能够创建这个即插即用解决方案:
function add_months($months, DateTime $dateObject) 
    {
        $next = new DateTime($dateObject->format('Y-m-d'));
        $next->modify('last day of +'.$months.' month');
        if($dateObject->format('d') > $next->format('d')) {
            return $dateObject->diff($next);
        } else {
            return new DateInterval('P'.$months.'M');
        }
    }
function endCycle($d1, $months)
    {
        $date = new DateTime($d1);
        // call second function to add the months
        $newDate = $date->add(add_months($months, $date));
        // goes back 1 day from date, remove if you want same day of month
        $newDate->sub(new DateInterval('P1D')); 
        //formats final date to Y-m-d form
        $dateReturned = $newDate->format('Y-m-d'); 
        return $dateReturned;
    }示例:
$startDate = '2014-06-03'; // select date in Y-m-d format
$nMonths = 1; // choose how many months you want to move ahead
$final = endCycle($startDate, $nMonths); // output: 2014-07-02发布于 2010-05-20 08:17:52
使用DateTime::add。
$start = new DateTime("2010-12-11", new DateTimeZone("UTC"));
$month_later = clone $start;
$month_later->add(new DateInterval("P1M"));我使用clone是因为add修改了原始对象,这可能并不是我们想要的。
https://stackoverflow.com/questions/2870295
复制相似问题