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.
您可以像这样计算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) :
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.