在ASP.NET中找到10月的最后一个星期日c#
Hii,有没有什么方法可以找到ASP.NET中我昨天使用的10月的最后一个星期日的日期.net 2.0
没有必要为此运行循环:
private static DateTime GetLastWeekdayOfMonth(DateTime date, DayOfWeek day) { DateTime lastDayOfMonth = new DateTime(date.Year, date.Month, 1) .AddMonths(1).AddDays(-1); int wantedDay = (int)day; int lastDay = (int)lastDayOfMonth.DayOfWeek; return lastDayOfMonth.AddDays( lastDay >= wantedDay ? wantedDay - lastDay : wantedDay - lastDay - 7); }
这可以很容易地转换为扩展方法,如下所示:
public static class DateTimeExtensions { public static DateTime GetLastWeekdayOfMonth(this DateTime date, DayOfWeek day) { DateTime lastDayOfMonth = new DateTime(date.Year, date.Month, 1) .AddMonths(1).AddDays(-1); int wantedDay = (int)day; int lastDay = (int)lastDayOfMonth.DayOfWeek; return lastDayOfMonth.AddDays( lastDay >= wantedDay ? wantedDay - lastDay : wantedDay - lastDay - 7); } }
…然后可以直接从任何DateTime对象使用:
DayOfWeek lastSunday = DateTime.Now.GetLastWeekdayOfMonth(DayOfWeek.Sunday);
更新:修复了一个错误。
你可以尝试这样的事情
DateTime date = new DateTime(2009, 10, 01); date = date.AddMonths(1).AddDays(-1); while (date.DayOfWeek != DayOfWeek.Sunday) date = date.AddDays(-1);
或者也试试
date = date.AddDays(-(int)date.DayOfWeek);
DateTime current = new DateTime(DateTime.Today.Year, 10, DateTime.DaysInMonth(DateTime.Today.Year, 10)); while (current.DayOfWeek != DayOfWeek.Sunday) { current = current.AddDays(-1); } Console.WriteLine(current.ToLongDateString());
我把它打开了,所以你可以很容易地用一个参数换掉月份。
抱歉
DateTime lastDayOfMonth = new DateTime(date.Year, date.Month, 1) .AddMonths(1).AddDays(-1);
是错的!
上述就是C#学习教程:在ASP.NET中找到10月的最后一个星期日c#分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
=> DateTime lastDayOfMonth = new DateTime(aYear, aMonth, DateTime.DaysInMonth(aYear, aMonth));
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/956824.html