0

我必须找出给定日期的月份中的哪一天,假设我有 2020 年 1 月 26 日的日期,现在日期 26 是本月的第四个星期日,我怎样才能找出它在月份中可重复计数的日期?

4

1 回答 1

1

没有直接的方法可以实现。您需要调用类似以下代码的内容。

 DateTime dateValue = new DateTime(2019, 12, 19);
        int getDayOfWeek = GetWeekNumberOfMonth(dateValue);
        //convert to ordinal 
       string ordinalWeekOfMonth = AddOrdinal(getDayOfWeek);
      Console.WriteLine(ordinalWeekOfMonth + " " + dateValue.DayOfWeek);//output like 2nd sunday

以下依赖方法可用于调用上述代码

     public static int GetWeekNumberOfMonth(DateTime date)
    {
        date = date.Date;
        DateTime firstMonthDay = new DateTime(date.Year, date.Month, 1);
        DateTime firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
        if (firstMonthMonday > date)
        {
            firstMonthDay = firstMonthDay.AddMonths(-1);
            firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
        }
        return (date - firstMonthMonday).Days / 7 + 1;
    }

    public static string AddOrdinal(int num)
    {
        if (num <= 0) return num.ToString();

        switch (num % 100)
        {
            case 11:
            case 12:
            case 13:
                return num + "th";
        }

        switch (num % 10)
        {
            case 1:
                return num + "st";
            case 2:
                return num + "nd";
            case 3:
                return num + "rd";
            default:
                return num + "th";
        }

    }
于 2019-12-13T18:07:35.453 回答