计算从给定日期开始的月份中的星期几? [英] Calculate the Week day of months from given date?

查看:100
本文介绍了计算从给定日期开始的月份中的星期几?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力寻找一种简单有效的解决方案来计算一个月中的星期几。例如,如果给定的日期是第一个星期一 2018年3月5日星期一,那么我想获取接下来6个月的每个月的第一个星期一的日期,例如: 2018年4月2日星期一 2018年5月3日星期一,依此类推。

I am struggling to find an easy and efficient solution to calculating the week day of a month. For example, if a given date is the first Monday Monday 5th March 2018 then I want to get the date for each first Monday of a month for the next 6 months e.g: Monday 2nd April 2018 and Monday 3rd May 2018 and so on.

我尝试使用这个问题。但是,下面的代码仅返回我希望它返回整个日期的星期数。

I have tried to use the following code from this question. However, the code below only returns the week number I would like it to return the whole date.

static class DateTimeExtensions
{
    static GregorianCalendar _gc = new GregorianCalendar();
    public static int GetWeekOfMonth(this DateTime time)
    {
        DateTime first = new DateTime(time.Year, time.Month, 1);
        return time.GetWeekOfYear() - first.GetWeekOfYear() + 1;
    }

    static int GetWeekOfYear(this DateTime time)
    {
        return _gc.GetWeekOfYear(time, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
    }
}

但是我很困惑,不知道如何可以修改上面的代码来解决此问题。任何帮助将不胜感激。

But I am confused and don't know how I can modify the above code to solve this issue. Any help will be appreciated.

推荐答案

只需在输入日期前加上4周,必要时再增加7天:

Just add 4 weeks to input date, add 7 more days if necessary:

static DateTime GetNextDate(DateTime d1)
{
    System.Diagnostics.Debug.Assert(d1.Day <= 28, "Behavior not described");
    DateTime d2 = d1.AddDays(28);
    // the following evaluates to 1 for 1-7, 2 for 8-14, etc
    int n1 = (d1.Day - 1) / 7 + 1;
    int n2 = (d2.Day - 1) / 7 + 1;
    if (n2 != n1)
    {
        d2 = d2.AddDays(7);
    }
    return d2;
}

样本输入和输出:

Thu 2018-Mar-01 > Thu 2018-Apr-05
Fri 2018-Mar-02 > Fri 2018-Apr-06
Sat 2018-Mar-03 > Sat 2018-Apr-07
Sun 2018-Mar-04 > Sun 2018-Apr-01
Mon 2018-Mar-05 > Mon 2018-Apr-02
Tue 2018-Mar-06 > Tue 2018-Apr-03
Wed 2018-Mar-07 > Wed 2018-Apr-04
Thu 2018-Mar-08 > Thu 2018-Apr-12
Fri 2018-Mar-09 > Fri 2018-Apr-13
Sat 2018-Mar-10 > Sat 2018-Apr-14
Sun 2018-Mar-11 > Sun 2018-Apr-08
Mon 2018-Mar-12 > Mon 2018-Apr-09
Tue 2018-Mar-13 > Tue 2018-Apr-10
Wed 2018-Mar-14 > Wed 2018-Apr-11
Thu 2018-Mar-15 > Thu 2018-Apr-19
Fri 2018-Mar-16 > Fri 2018-Apr-20
Sat 2018-Mar-17 > Sat 2018-Apr-21
Sun 2018-Mar-18 > Sun 2018-Apr-15
Mon 2018-Mar-19 > Mon 2018-Apr-16
Tue 2018-Mar-20 > Tue 2018-Apr-17
Wed 2018-Mar-21 > Wed 2018-Apr-18
Thu 2018-Mar-22 > Thu 2018-Apr-26
Fri 2018-Mar-23 > Fri 2018-Apr-27
Sat 2018-Mar-24 > Sat 2018-Apr-28
Sun 2018-Mar-25 > Sun 2018-Apr-22
Mon 2018-Mar-26 > Mon 2018-Apr-23
Tue 2018-Mar-27 > Tue 2018-Apr-24
Wed 2018-Mar-28 > Wed 2018-Apr-25

这篇关于计算从给定日期开始的月份中的星期几?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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