Gol*_*old 294 .net c# datetime
如何在C#中找到该月的最后一天?
例如,如果我的日期是03/08/1980,那么如何获得第8个月的最后一天(在这种情况下为31)?
Osk*_*lin 601
这个月的最后一天,你得到这样的,返回31:
DateTime.DaysInMonth(1980, 08);
Run Code Online (Sandbox Code Playgroud)
Mar*_*ark 169
var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month);
Run Code Online (Sandbox Code Playgroud)
Hen*_*man 82
DateTime firstOfNextMonth = new DateTime(date.Year, date.Month, 1).AddMonths(1);
DateTime lastOfThisMonth = firstOfNextMonth.AddDays(-1);
Run Code Online (Sandbox Code Playgroud)
ins*_*ite 34
如果你想要一个月和一年的日期,这似乎是正确的:
public static DateTime GetLastDayOfMonth(this DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, DateTime.DaysInMonth(dateTime.Year, dateTime.Month));
}
Run Code Online (Sandbox Code Playgroud)
Rad*_*094 10
从下个月的第一天开始减去一天:
DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month+1,1).AddDays(-1);
Run Code Online (Sandbox Code Playgroud)
此外,如果您需要它也适用于12月:
DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month,1).AddMonths(1).AddDays(-1);
Run Code Online (Sandbox Code Playgroud)
小智 9
您可以按如下方式扩展 DateTime;
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);
}
}
Run Code Online (Sandbox Code Playgroud)
并按如下方式使用它;
DateTime today = DateTime.Now;
DateTime startOfMonth = today.StartOfMonth();
DateTime endOfMonth = today.EndOfMonth();
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以通过以下代码找到任何月份的最后日期:
var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year, now.Month, 1);
var DaysInMonth = DateTime.DaysInMonth(now.Year, now.Month);
var lastDay = new DateTime(now.Year, now.Month, DaysInMonth);
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以通过一行代码找到该月的最后一天:
int maxdt = (new DateTime(dtfrom.Year, dtfrom.Month, 1).AddMonths(1).AddDays(-1)).Day;
Run Code Online (Sandbox Code Playgroud)
从 DateTimePicker:
第一次约会:
DateTime first_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, 1);
Run Code Online (Sandbox Code Playgroud)
最后日期:
DateTime last_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, DateTime.DaysInMonth(DateTimePicker.Value.Year, DateTimePicker.Value.Month));
Run Code Online (Sandbox Code Playgroud)
// Use any date you want, for the purpose of this example we use 1980-08-03.
var myDate = new DateTime(1980,8,3);
var lastDayOfMonth = new DateTime(myDate.Year, myDate.Month, DateTime.DaysInMonth(myDate.Year, myDate.Month));
Run Code Online (Sandbox Code Playgroud)