[英]How to get the Date time month start and End Date?
How to get the start date and end date of month in different variable. 如何在不同的变量中获取月份的开始日期和结束日期。 I have tried this and I get the start date but unable to find the 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");
This logic fails when month end date is 31 and 28 or 29. Your Help are surely appretiated. 当月结束日期为31和28或29时,此逻辑将失败。您的帮助肯定是有用的。
您可以像这样计算endDate
:
DateTime endDate = startDate.AddMonths(1).AddDays(-1);
To get First Date 获得第一次约会
public DateTime FirstDayOfMonth(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, 1);
}
To get Last Date 获取最后日期
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);
You already had the start date : 你已经有了开始日期:
DateTime monthStartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
There's a method to get the number of days in a month (and Looking at the IL code, it seems that this way is more efficient than the other answers, though unless you're going to do it a billion time, I doubt there will be any difference) : 有一种方法可以获得一个月的天数(看看IL代码,看起来这种方式比其他答案更有效,但除非你要做十亿次,我怀疑会有有任何区别):
int daysInMonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
DateTime monthEndDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, daysInMonth);
For first date: 第一次约会:
DateTime first_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, 1);
For last date: 最后日期:
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.