首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >日期计算错误

日期计算错误
EN

Stack Overflow用户
提问于 2015-10-25 16:42:37
回答 2查看 443关注 0票数 0

我有一个简单的代码,它将一个月的日期(DD/MM/YYYY)设置为Column in Excel

代码语言:javascript
运行
复制
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);
}

其结果是:

01/2015

01/02/2015

01/03/2015

01/04/2015

01/05/2015

01/06/2015

01/07/2015

01/08/2015

01/09/2015

2015年10月1日

2015年11月1日

2015年12月1日

2015年1月13日

14/01/2015

2015年1月15日

..。

因此,只有1到12是有问题的。

编辑:

代码语言:javascript
运行
复制
int daysInMonth = DateTime.DaysInMonth(int.Parse(year.Text), int.Parse(month.Text));
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-10-25 16:55:22

问题是,在for-循环的每一次迭代之后,都不会更新日期。我是说你这样做是错误的:

date.AddDays(1.0);//这将返回一个值,但永远不会将它分配给日期本身。

你应该用这样的方法:

代码语言:javascript
运行
复制
date = date.AddDays(1.0);

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

解决方案:将日期存储为1900年1月1日(办公室支助)之后的天数。因此,您可以根据该格式设置单元格的值,然后将单元格的数字格式更改为通常设置为"DD/MM/YYYY“的格式。

从date:获得整数值的函数:

代码语言:javascript
运行
复制
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
}

现在,您可以像这样使用代码:

代码语言:javascript
运行
复制
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);
}
票数 3
EN

Stack Overflow用户

发布于 2015-10-25 17:48:22

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

代码语言:javascript
运行
复制
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");
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33332215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档