Strange Formatexception dopo l'aggiornamento in VS 2010
-
13-09-2020 - |
Domanda
ottengo questa formatexception dopo aver aggiornato a VS 2010. Non niente di speciale. Codice:
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;
}
.
Diciamo che stai ora se esegui questo 31/6/2010.Penso che sia una data valida. Ho testato la data che viene generata e va bene ... Questo progetto non ha mai avuto questo problema mentre stava lavorando in VS 2008.
Qualche idea?
Soluzione
Il FormatException
è causato dal passaggio 31/6/2010
come argomento a DateTime.Parse()
.31/6/2010 non è una data valida - ci sono solo 30 giorni a giugno.
Se hai bisogno dell'ultimo giorno in qualsiasi mese, è meglio utilizzare il DateTime.DaysInMonth()
Metodo.Ci vuole sia il mese che l'anno come argomenti in modo che possa affrontare gli anni del salto.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow