date计算错误
我有一个简单的代码,将月份的date(DD/MM/YYYY)
为Excel
的Column
:
DateTime date = new DateTime(int.Parse(year.Text), int.Parse(month.Text), 1); //year.Text & month.Text are just the month and year from controls in the form. for (int j = 7; j < daysInMonth + 7; j++) { sheet.get_Range("A" + j).Value = date.ToShortDateString(); date.AddDays(1.0); }
其结果是:
2015年1月1日
2015年1月2日
2015年1月3日
2015年1月4日
2015年1月5日
2015年1月6日
2015年1月7日
2015年1月8日
2015年1月9日
2015年1月10日
2015年1月11日
2015年1月12日
13/01/2015
14/01/2015
15/01/2015
…
所以,只有1到12是有问题的。
编辑:
int daysInMonth = DateTime.DaysInMonth(int.Parse(year.Text), int.Parse(month.Text));
问题在于,在for循环的每次迭代之后,您都不更新date。 我的意思是你这样做是错误的:
date.AddDays(1.0); //This returns a value but you never assign it to the date itself.
你应该使用这样的东西:
date = date.AddDays(1.0);
更新:上面的部分是你的代码轻微的问题。 主要的问题是Excel本身。 当你通过一个date低于13日的date时,无论是提供给它的格式,它都会混淆是月份还是date。
解决方法: Excel将date存储为1900年1月1日之后的天数( Office支持 )。 所以你可以根据这个格式设置单元格的值,然后把单元格的数字格式改成你通常设置为格式“DD / MM / YYYY”的格式。
从date获取整数值的函数:
private int convertDateTime(DateTime input) { DateTime start = new DateTime(1900, 1, 1); return (int)(input - start).TotalDays + 2; //This is some calibration with the above mentioned Office article }
现在,你可以像这样使用你的代码:
DateTime date = new DateTime(int.Parse(year.Text), int.Parse(month.Text), 1); //year.Text & month.Text are just the month and year from controls in the form. for (int j = 7; j < daysInMonth + 7; j++) { Range cell = sheet.get_Range("A" + j); cell.Value = convertDateTime(date); cell.NumberFormat = "DD/MM/YYYY"; date = date.AddDays(1.0); }
尝试对循环内的单元格位置进行计数,并在将其设置为表单之前增加date,如下所示:
DateTime date = new DateTime(int.Parse(year.Text), int.Parse(month.Text), 1); for (int j = 0; j < daysInMonth; j++) { // Skip increasing the first date if (j > 0) { date = date.AddDays(1.0); } // Set the correct date to the sheet sheet.get_Range("A" + (j + 7)).Value = date.ToString(@"dd/MM/yyyy"); }