得到一个月份的第一天和最后一天,使用给定的DateTime对象天和、对象、DateTime

2023-09-02 23:49:47 作者:亡鱼深海花夕拾

我想获得其中给定日期在于该月的第一天并最后一天的日期来源于在UI字段的值。

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;

不过,我想从一个DateTime对象得到它。所以,如果我有这样的...

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

DateTime dt = DateTime.today;

如何获得第一日,月的最后一天,从 DT

推荐答案

DateTime结构只存储一个值,不值的范围内。 MINVALUE 的MaxValue 是静态字段,按住实例可能值范围日期时间结构。这些字段是静态的,不涉及的DateTime 的特定实例。它们涉及到的DateTime 键入自己。

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 does not relate to particular instance of DateTime. They relate to DateTime type itself.

推荐阅读:静态(C#参考)

更新:获取每月范围:

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