在ASP.NET C#中查找日期十月的最后一个星期日 [英] Find the date Last sunday of October in ASP.NET c#

查看:80
本文介绍了在ASP.NET C#中查找日期十月的最后一个星期日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hii,有什么办法可以在ASP.NET C#中找出十月的最后一个星期日的日期.我正在使用.net 2.0

Hii, Is there any way to find out the date in which last sunday of October in ASP.NET c# I am using .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);
}

可以轻松地将其转换为扩展方法,如下所示:

This can easily be converted into an extension method, like so:

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对象中使用:

...and can then be used directly from any DateTime object:

DayOfWeek lastSunday = DateTime.Now.GetLastWeekdayOfMonth(DayOfWeek.Sunday);

更新:修复了一个错误.

Update: fixed a bug.

这篇关于在ASP.NET C#中查找日期十月的最后一个星期日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆