views:

20

answers:

1

I get this FormatException after i upgraded to VS 2010. Not anything really special. Code:

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;
}

Lets say you get now if you run this 31/6/2010. I think its a valid date. I have tested the date that is generated and its ok...this project never had this problem while was working in VS 2008.

Any ideas?

+1  A: 

Your FormatException is caused by passing 31/6/2010 as an argument to DateTime.Parse(). 31/6/2010 is not a valid date - there are only 30 days in June.

If you need the last day in any month, you would be better off using the DateTime.DaysInMonth() method. It takes both the month and year as arguments so it can deal with leap years.

adrianbanks
My god, how i could not see this.....
AlwaysBeCoding
@AlwaysBeCoding, since this response answers your question, you should make sure you check the outline of a "tick" next to the answer to mark it as "accepted".
Dean Harding