c#在上个月的基础上添加正确的月份

c#在上个月的基础上添加正确的月份,c#,date,datetime,C#,Date,Datetime,我正在尝试将一个月添加到日期,并基于上个月填充文本框。在31日(甚至2月28日)结束的几个月里,这项工作都很有效。但是,如果上一个月在30日结束,下一个月在31日结束,那么它要么短一天,要么长一天。例如: 上次开工日期:2017年4月1日 上一个结束日期:2017年4月30日 新开工日期:2017年5月1日 新的结束日期:应为2017年5月31日 以下是我的代码: // Set the Start Date DateTime dtNewStartDate; dtNewStartDate = Co

我正在尝试将一个月添加到日期,并基于上个月填充文本框。在31日(甚至2月28日)结束的几个月里,这项工作都很有效。但是,如果上一个月在30日结束,下一个月在31日结束,那么它要么短一天,要么长一天。例如:

上次开工日期:2017年4月1日
上一个结束日期:2017年4月30日
新开工日期:2017年5月1日
新的结束日期:应为2017年5月31日

以下是我的代码:

// Set the Start Date
DateTime dtNewStartDate;
dtNewStartDate = Convert.ToDateTime(txtRecentBeginDate.Text).AddMonths(1);
txtNewStartDate.Text = dtNewStartDate.ToString();

// Set the End Date
DateTime dtNewEndDate;
dtNewEndDate = Convert.ToDateTime(txtNewStartDate.Text).AddMonths(1);
txtNewEndDate.Text = dtNewEndDate.ToString();
这将产生2017年6月1日的结束日期,而不是2017年5月31日

编辑:我能从中找到我想要的东西。 此解决方案考虑闰年,并在任何情况下获得正确的月份最后一天。这就是我想到的:

// Set the End Date
int intYear = dtNewStartDate.Year;
int intMonth = dtNewStartDate.Month;
int intNumberOfDays = DateTime.DaysInMonth(intYear, intMonth);
DateTime dtNewEndDate = new DateTime(intYear, intMonth, intNumberOfDays);
txtNewEndDate.Text = dtNewEndDate.ToString();

我通常是这样做的:从开始日期开始计算年份和月份,在此基础上创建一个新的日期,加上一个月,减去下一个月的最后一天:

DateTime dtNewEndDate = new DateTime(dtNewStartDate.Year, dtNewStartDate.Month, 1)
    .AddMonths(1)
    .AddDays(-1);

你可以得到当月的最后一天

 DateTime today = DateTime.Today;
 DateTime endOfMonth = new DateTime(today.Year, 
                               today.Month, 
                               DateTime.DaysInMonth(today.Year, 
                                                    today.Month));

我不明白你想干什么。你能扩展一下“我正试图在一个日期上加上一个月,并基于上个月填充文本框”吗?你的两个代码示例是相同的。正是finrod所说的。如何从同一代码段中获得两个不同的输出?可能是重复的