2013-04-22 46 views
2

在PHP中,如果你這樣做:獲得MySQL DATE_ADD相同的工作,如PHP

$date = "2013-08-31"; 
$nextdate = strtotime(date("Y-m-d", strtotime($date)) . " +1 month"); 
$date = date("Y-m-d", $nextdate); 
echo $date; 

你得到2013年10月1日即一個月翻了,因爲只有30天九月。

在MySQL中,如果你這樣做:

UPDATE member_account SET NextBillDate = '2013-08-31' 
SELECT DATE_ADD(NextBillDate, INTERVAL 1 MONTH) FROM member_account 

你得到2013年9月30日即沒有翻車

在Java中這是同樣的事情:

GregorianCalendar oDate = new GregorianCalendar(); 
SimpleDateFormat Sdf = new SimpleDateFormat("yyyy-MM-dd"); 
try{oDate.setTime(Sdf.parse("2013-08-31"));} catch (Exception e) {} 
String sTodayDate = Sdf.format(oDate.getTime()); 

oDate.add(Calendar.MONTH, 1); 
String sTodayDate2 = Sdf.format(oDate.getTime()); 

sTodayDate2是「 2013-09-31「

有沒有辦法使MySQL或Java的行爲方式與PHP相同,所以它會翻轉,如果該月的天數已超過?

+1

如果你想31天​​,寫'間隔31 day' – Barmar 2013-04-22 19:39:21

+0

最好的選擇是建立在PHP的日期,以及該變量傳遞到您的聲明。 DATE_ADD函數自動將其設置爲下個月的最後一天,如果它超過了日期。我沒有意識到任何其他的SQL函數可以做你需要的。 – 2013-04-22 19:41:49

+0

@Barmar - 我想要1個月,而不是31天。 – BigMeat 2013-04-22 19:49:01

回答

0

發現這個小Java代碼,做的伎倆:

int oldDay = oDate.get(Calendar.DAY_OF_MONTH); 
    oDate.add(Calendar.MONTH, 1); 

    // If the old DAY_OF_MONTH was larger than our new one, then 
    // roll over to the beginning of the next month. 
    if (oldDay > oDate.get(Calendar.DAY_OF_MONTH)){ 
     oDate.add(Calendar.MONTH, 1); 
     oDate.set(Calendar.DATE, 1); 
    } 

    String sTodayDate2 = Sdf.format(oDate.getTime());