我想要得到给定日期所在月份的第一天和最后一天。日期来自UI字段中的值。

如果我使用时间选择器,我可以说

var maxDay = dtpAttendance.MaxDate.Day;

但我试图从DateTime对象中获取它。如果我有这个。

DateTime dt = DateTime.today;

如何从dt中获取每月的第一天和最后一天?


当前回答

你可以做到的

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

其他回答

很简单

Begin = new DateTime(DateTime.Now.Year, DateTime.Now.Month,1).ToShortDateString();
End = new DataFim.Text = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)).ToShortDateString();

对于波斯文化来说

PersianCalendar pc = new PersianCalendar();            

var today = pc.GetDayOfMonth(DateTime.Now);
var firstDayOfMonth = pc.GetDayOfMonth(DateTime.Now.AddDays(-(today-1)));
var lastDayOfMonth = pc.GetDayOfMonth(DateTime.Now.AddMonths(1).AddDays(-today));            
Console.WriteLine("First day "+ firstDayOfMonth);
Console.WriteLine("Last day " + lastDayOfMonth);

你可以试着得到本月的第一天;

DateTime.Now.AddDays(-(DateTime.Now.Day-1))

给它赋一个值。

是这样的:

dateEndEdit.EditValue = DateTime.Now;
dateStartEdit.EditValue = DateTime.Now.AddDays(-(DateTime.Now.Day-1));
DateTime dCalcDate = DateTime.Now;
dtpFromEffDate.Value = new DateTime(dCalcDate.Year, dCalcDate.Month, 1);
dptToEffDate.Value = new DateTime(dCalcDate.Year, dCalcDate.Month, DateTime.DaysInMonth(dCalcDate.Year, dCalcDate.Month));

创建一个DateTime类的实例

DateTime dateTime = DateTime.Now;

如果你想要得到这个月的最后一天,你可以这样做

int lastDayOfMonth = DateTime.DaysInMonth(caducidadPuntos.Year, caducidadPuntos.Month);

如果你想得到每月的第一天,你可以这样做

DateTime firstDayMonth = new DateTime(dateTime.Year, dateTime.Month, 1);