When I write reports, usually some of them need to use a date range. For example, the user wants to include all their account transactions for the month.
Here are two extension methods I use to calculate the dates for the beginning and end of the month (down to the second).
using System; namespace DotNetToolBox { public static class DateTimeMethods { public static DateTime StartOfMonth(this DateTime date) { return new DateTime(date.Year, date.Month, 1, 0, 0, 0); } public static DateTime EndOfMonth(this DateTime date) { return date.StartOfMonth().AddMonths(1).AddSeconds(-1); } } }
It’s simple to use them. Just do this, to get variables for the beginning and end of the current month:
DateTime today = DateTime.Now; DateTime startOfMonth = today.StartOfMonth(); DateTime endOfMonth = today.EndOfMonth();
These are extremely useful methods to add to your “toolbox” library (which, every good developer should have).