如何获取日期时间月份开始和结束日期?

时间:2014-04-15 07:31:20

标签: c# date datetime

如何在不同变量中获取月份的开始日期和结束日期。我已经尝试了这个,但我得到了开始日期但无法找到结束日期

DateTime startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy-MM-dd HH:mm:ss.fff");
DateTime  endDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(30).ToString("yyyy-MM-dd HH:mm:ss.fff");

当月末日期为31和28或29时,此逻辑失败。您的帮助肯定会有所帮助。

5 个答案:

答案 0 :(得分:33)

您可以像这样计算endDate

DateTime endDate = startDate.AddMonths(1).AddDays(-1);

答案 1 :(得分:14)

获得第一个日期

public DateTime FirstDayOfMonth(DateTime dateTime)
{
   return new DateTime(dateTime.Year, dateTime.Month, 1);
}

获取上次日期

public DateTime LastDayOfMonth(DateTime dateTime)
{
   DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
   return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
}

答案 2 :(得分:1)

DateTime endDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)
                       .AddMonths(1).AddDays(-1);

答案 3 :(得分:1)

您已经有了开始日期:

DateTime monthStartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

有一种方法可以获得一个月内的天数(看看IL代码,看起来这种方式比其他答案更有效,但除非你要做十亿次,我怀疑会有什么不同):

int daysInMonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
DateTime monthEndDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, daysInMonth);

答案 4 :(得分:-2)

第一次约会:

DateTime first_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, 1);

最后日期:

DateTime last_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, DateTime.DaysInMonth(DateTimePicker.Value.Year, DateTimePicker.Value.Month));
相关问题