首页 文章

使用月份确定日期的简单公式?

提问于
浏览
6

给定一个标准的调度信息,例如“2009年6月的第二个星期二”或“2009年7月的最后一个星期五”,将这个信息转换为日期的最简单,最有效的公式是什么?

Inputs:

  • w =月份,枚举(第1,第2,第3,第4或最后)

  • d =星期几,星期日到星期六

  • m =月,整数

  • y =年份,整数

EDIT (again) - 本周哪一天开始并不重要;我想在给定的月份得到d的wth实例 . 因此,2009年6月的第2个星期日是6月14日,即使技术上属于6月的第3周;同样,6月的第一个星期日是6月7日,不是空/例外 .

3 回答

  • 0

    就像是:

    static DateTime GetDate(int year, int month, DayOfWeek dayOfWeek,
            int weekOfMonth) {
        // TODO: some range checking (>0, for example)
        DateTime day = new DateTime(year, month, 1);
        while (day.DayOfWeek != dayOfWeek) day = day.AddDays(1);
        if (weekOfMonth > 0) {
            return day.AddDays(7 * (weekOfMonth - 1));
        } else { // treat as last
            DateTime last = day;
            while ((day = day.AddDays(7)).Month == last.Month) {
                last = day;
            }
            return last;
        }
    }
    
  • 8

    当工作日要求时,编辑修复错误与月初的一天相同 .

    第二次编辑修复问题光盘'由Marc

    static DateTime GetDate(int year, int month, 
                    DayOfWeek weekDay, int week)
    {  
        DateTime first = new DateTime(year, month, 1);
        int iDow = (int)weekday, iFirst = (int)first.DayOfWeek;
        int adjust = (7+iDow-iFirst)%7 - 7;
        return first.AddDays(7*week + adjust);
    }
    
  • 1
    using System;
    
    namespace date_using_week_of_month
    {
    
        public class Example
        {
            public static DateTime WthDayDOfMonthM( int w, DayOfWeek d, DateTime month )
            {
                return first( d, month ).AddDays( 7 * (w - 1) );
            }
    
            private static DateTime first( DayOfWeek d, DateTime month )
            {
                DateTime first = new DateTime(
                    month.Year, month.Month, 1 );
                while ( first.DayOfWeek != d )
                {
                    first = first.AddDays( 1 );
                }
                return first;
            }
        }
    }
    

相关问题