2010-07-12 86 views
0

升級到VS 2010後,我得到這個FormatException。沒有什麼特別的。 代碼:VS 2010中升級後奇怪的FormatException

private void ManageDateEditControls() 
{ 
    apoDateEdit.DateTime = DateTime.Parse(string.Format("01/{0}/{1}", DateTime.Now.Month-1, DateTime.Now.Year)); 
    eosDateEdit.DateTime = DateTime.Parse(string.Format("{0}/{1}/{2}", GetLastDayOfMonth(DateTime.Now.Month + 1), 
     DateTime.Now.Month - 1, DateTime.Now.Year)); <-- FormatException occurs in this line. 
} 

private static int GetLastDayOfMonth(int month) 
{ 
    // set return value to the last day of the month 
    // for any date passed in to the method 

    // create a datetime variable set to the passed in date 
    DateTime dtTo = new DateTime(DateTime.Now.Year, month, 1); 

    // overshoot the date by a month 
    dtTo = dtTo.AddMonths(1); 

    // remove all of the days in the next month 
    // to get bumped down to the last day of the 
    // previous month 
    dtTo = dtTo.AddDays(-(dtTo.Day)); 

    // return the last day of the month 
    return dtTo.Day; 
} 

比方說,你現在得到,如果你運行31/6/2010。我認爲它是一個有效的日期。 我測試了生成的日期和它的好...這個項目在VS 2008中工作時從未遇到過這個問題。

任何想法?

+0

我有點困惑 - 爲什麼31/6/2010是有效日期? – 2010-07-12 00:15:23

回答

1

您的FormatException是由傳遞31/6/2010作爲參數DateTime.Parse()引起的。 31/6/2010不是有效日期 - 六月份只有30天。

如果您需要在任何月份的最後一天,最好使用DateTime.DaysInMonth()方法。它需要將月份和年份作爲參數,以便處理閏年。

+0

我的上帝,我怎麼看不到這個..... – AlwaysBeCoding 2010-07-12 00:10:08

+0

@AlwaysBeCoding,因爲這個答案回答你的問題,你應該確保你檢查答案旁邊的「勾號」的大綱以將其標記爲「接受」 。 – 2010-07-12 00:11:42

相關問題