C# 4.0 VS 2010升级后出现奇怪的格式异常
升级到VS 2010后,我收到了此格式异常。没有什么特别的。 代码:C# 4.0 VS 2010升级后出现奇怪的格式异常,c#-4.0,formatexception,C# 4.0,Formatexception,升级到VS 2010后,我收到了此格式异常。没有什么特别的。 代码: 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}”),GetLa
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));您的格式异常是由于将31/6/2010
作为参数传递给DateTime.Parse()
.31/6/2010不是有效日期-6月只有30天
如果您需要任何月份的最后一天,最好使用该方法。它将月份和年份作为参数,以便处理闰年。@AlwaysBeCoding,由于此回答回答了您的问题,您应该确保检查答案旁边的“勾号”提纲,将其标记为“已接受”.我有点困惑-为什么2010年6月31日是有效日期?
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;
}