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

CAD picture CAD · Jun 16, 2014 · Viewed 287.7k times · Source

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?

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Jun 16, 2014

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);