繁体   English   中英

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

[英]How to get the Date time month start and End Date?

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

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时,此逻辑将失败。您的帮助肯定是有用的。

您可以像这样计算endDate

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

获得第一次约会

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);
}
DateTime endDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)
                       .AddMonths(1).AddDays(-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);

第一次约会:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM