I am working with dates in C# and need to calculate some further dates. Taking the current datetime
.
How can I get the following values?
- end of day
- end of month
- end of year
I am working with dates in C# and need to calculate some further dates. Taking the current datetime
.
How can I get the following values?
If by end of ...
you mean 12:59:59.999PM
at that day then:
end of day
var today = DateTime.Today;
var endOfDay = new DateTime(
today.Year,
today.Month,
today.Day,
23,
59,
59,
999
);
end of month
var today = DateTime.Today;
var endOfMonth = new DateTime(
today.Year,
today.Month,
DateTime.DaysInMonth(today.Year, today.Month),
23,
59,
59,
999
);
end of year
var today = DateTime.Today;
var endOfYear = new DateTime(
today.Year,
12,
31,
23,
59,
59,
999
);
If you mean something else, then explain what you mean.
For end of month
DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month));
see How can I get the last day of the month in C#?
For end of year
DateTime endOfYear = new DateTime(today.Year, 12, 31);
For end of day, assuming the end of day is close of business at 5 PM
DateTime endOfDay = new DateTime(today.Year, today.Month, today.day, 17, 0, 0); // Assuming the business end of day is at 5 PM
See more about datetime at http://msdn.microsoft.com/en-us/library/system.datetime.aspx
Last day of month:
DateTime today = DateTime.Now;
DateTime lastDayOfMonth = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month));
Last day of year:
DateTime today = DateTime.Now;
DateTime lastDayOfYear = new DateTime(today.Year, 12, 31);