C# – Getting the first and last day of a month, using a given DateTime object

cdatetimenetwinforms

I want to get the first day and last day of the month where a given date lies in. The date comes from a value in a UI field.

If I'm using a time picker I could say

var maxDay = dtpAttendance.MaxDate.Day;

But I'm trying to get it from a DateTime object. So if I have this…

DateTime dt = DateTime.today;

How to get first day and last day of the month from dt?

Best Answer

DateTime structure stores only one value, not range of values. MinValue and MaxValue are static fields, which hold range of possible values for instances of DateTime structure. These fields are static and do not relate to particular instance of DateTime. They relate to DateTime type itself.

Suggested reading: static (C# Reference)

UPDATE: Getting month range:

DateTime date = ...
var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);