获得一个指定星期的起始和终止日期
在做一个项目的时候,
一、需要得到给定日期所属的星期,按星期统计。
二、然后得到这个星期的起始终止日期。
好像没有找到现成的方法,只能自己做一个。
觉得效率差了些,时间复杂度为O(365),不知道是否有更好的方法。

        [TestMethod]
        [Description("测试某星期的其实终止日期")]
        public void testWeekDateScop()
        {
            //就测试这天了
            DateTime testDate = new DateTime(2005, 8, 28);
           
            //选择合适的日历
            System.Globalization.Calendar calendar = new System.Globalization.GregorianCalendar();

            //把指定日期转换成年和所在星期
            int theYear = calendar.GetYear(testDate);
            int theWeek = calendar.GetWeekOfYear(testDate, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday);

            //得到指定星期的起始终止日期
            DateTime fromDate = DateTime.MinValue;
            DateTime toDate = DateTime.MinValue ;

            //从一年的第一天到最后一天
            for ( int i = 0; i < calendar.GetDaysInYear(theYear); i++ )
            {
                //一年的第一天,到指定距离的日期
                DateTime thisDay = calendar.AddDays(new DateTime(theYear, 1, 1), i);
                //此处要和取得星期的策略一样(theWeek值)
                int curWeek = calendar.GetWeekOfYear(thisDay, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday);
                if ( curWeek == theWeek )
                {
                    if ( fromDate == DateTime.MinValue ) fromDate = thisDay;
                    toDate = thisDay;
                }
            }

            TestContext.WriteLine("{0}年  第{1}周 星期:{4}  起始日期:{2}  终止日期:{3}", theYear, theWeek, fromDate, toDate, calendar.GetDayOfWeek(testDate).ToString());
        }

改进一下,复杂度变为,最好O(7),最差为(365),这只能这样了
                if ( curWeek == theWeek )
                {
                    if ( fromDate == DateTime.MinValue ) fromDate = thisDay;
                    toDate = thisDay;
                }
                else if ( fromDate != DateTime.MinValue )
                    break;

结果:
2005年 
第35周
星期:Sunday 
起始日期:2005-8-22 0:00:00 
终止日期:2005-8-28 0:00:00

posted on 2011-07-27 15:53  老闪  阅读(303)  评论(0)    收藏  举报