2016-07-22 60 views
6

我在PHP中的日期有一個小問題。日期加上一個月php

當我提出了31 + 1個月 月的這段代碼

$newDate = date('Y-m-d', strtotime('31-01-2016'.' + 1 month')); 
echo $newDate; 

它給了我3月2日,但我需要給我2月29日,

我需要1個月的補充,而不是30天。

同上所有日期: 例如 一月一日+ 1個月=> 2月1日

1月29日+ 1個月=> 2月29日

1月30日+ 1個月=> 2月29日

1月31日+ 1個月=> 2月29日

感謝您的幫助

+0

二月29 1月30日之後不到一個月。我沒有看到問題。 – apokryfos

+1

我希望有沒有直接的功能在PHP中實現它... – user1844933

+0

https://eval.in/610030 – splash58

回答

5

我認爲你正在尋找這種類型的日期。

<?php 
    $date = date('2016-01-31'); 
    $currentMonth = date("m",strtotime($date)); 
    $nextMonth = date("m",strtotime($date."+1 month")); 
    if($currentMonth==$nextMonth-1){ 
     $nextDate = date('Y-m-d',strtotime($date." +1 month")); 
    }else{ 
     $nextDate = date('Y-m-d', strtotime("last day of next month",strtotime($date))); 
    } 
    echo "Next date would be : $nextDate"; 
?> 

檢查現場演示:https://eval.in/610034

  1. 如果日期是31-01-2016那麼接下來的日期將是29-02-2016
  2. 如果日期是25-01-2016那麼接下來的日期將是25-02-2016
3

簡單地嘗試:

$date = new DateTime('2016-01-31'); 
$date->modify('last day of next month'); 

這當然只有計數,如果你總是從一個飛蛾結束到下一個結束。

+1

我個人首先做一個'+1月',並檢查新月是不是'(前+ 1)%12'然後這樣做。 – apokryfos

+0

@apokryfos你是對的。那麼最好使用'next month',不是嗎? – Barthy

+0

我不認爲有一個單一的計算來獲得OP的預期結果,因爲這是一個非標準的事情。 – apokryfos

1

試試這個,

$date = "2016-01-29"; 
$date = date('Y-m-d', strtotime("last day of next month",strtotime($date))); 
echo $date; 

https://3v4l.org/Y9PpV

0

怎麼是這樣的:

date_default_timezone_set('UTC'); 

$current_month = (int) date('m'); 
$year = date('y'); 
$newDate = date('Y-m-d', strtotime('31-1-2016'.' + 1 month')); 

if($current_month == 12) 
{ 
    $new_month=0; 
    $year++; 
} 

$d = new DateTime($year.'-'.($current_month+1).'-01'); 
echo $d->format('Y-m-t')."\n"; 

更改$ current_month /根據您的需求$一年......