0

升级到 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;
}

如果您在 2010 年 6 月 31 日运行,假设您现在得到。我认为这是一个有效的日期。我已经测试了生成的日期并且没问题......这个项目在 VS 2008 中工作时从未遇到过这个问题。

有任何想法吗?

4

1 回答 1

1

FormatException是由31/6/2010作为参数传递给DateTime.Parse(). 2010 年 6 月 31 日不是有效日期 - 六月只有 30 天。

如果您需要任何一个月的最后一天,最好使用该DateTime.DaysInMonth()方法。它需要月份和年份作为参数,因此它可以处理闰年。

于 2010-07-12T00:08:43.897 回答