日期计算错误

时间:2015-10-25 16:42:37

标签: c# excel winforms date

我有一个简单的代码,可以在Column中将一个月的Excel日期设置为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); }

int daysInMonth = DateTime.DaysInMonth(int.Parse(year.Text), int.Parse(month.Text));

结果是:
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是有问题的。

修改

public static void main(String args[]){
  Date d1 = new Date(99,11,31);
  Date d2 = new Date(99,11,31);
  changeDate(d1,d2);
  System.out.println("d1: "+d1+" \nd2: "+d2);
}
static void changeDate(Date d1, Date d2){
  d1.setYear(100);
  d2 = d1;
}

2 个答案:

答案 0 :(得分:3)

问题是你不能在for循环的每次迭代后更新日期。我的意思是你这样做的方式不对:

date.AddDays(1.0); //This returns a value but you never assign it to the date itself.

你应该使用这样的东西:

date = date.AddDays(1.0);

更新:以上部分是您的代码的一个小问题。主要问题是Excel本身。当您将日期低于13的日期传递时,无论您提供给它的格式如何,都会混淆是月份还是日期。

解决方法: Excel将日期存储为1900年1月1日(Office Support)之后的天数。因此,您可以根据该格式设置单元格的值,然后将单元格的数字格式更改为您通常设置的格式 - “DD / MM / YYYY”。

从日期获取整数值的函数:

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

答案 1 :(得分:2)

尝试计算循环内的单元格位置并在将其设置为工作表之前增加日期,如下所示:

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");
}
相关问题