c#

 

        /// <summary>
        
/// 获取指定日期为指定年月份的第几周
        
/// </summary>
        public int GetWeekOfMonth(DateTime date)
        {
            DateTime firstDayInMonth 
= DateTime.Parse(string.Format("{0}-{1}-01", date.Year, date.Month));

            
//不计入本月周的总天数,如1号为星期五,则1、2、3都不计入将要计算的周内
            int exceptDays = 0;

            
if (firstDayInMonth.DayOfWeek != DayOfWeek.Monday)
            {
                
//+ 2的含义为计算时需要减去1号和date当天的日期
                
//如果不减去date当天,则当date为星期天时,则刚好在除7后为正确值,再加1就会多一周
                exceptDays = 7 - (int)firstDayInMonth.DayOfWeek + 2;
            }

            
//指定的日期减去不计算在周内的日期数
            return (date.Day - exceptDays) / 7 + date.Day < exceptDays ? 0 : 1;
        }

 

SQL:

 

DECLARE @Date DateTime 
SET @Date = '2009-06-29'

SELECT CASE WHEN (DATEPART(WEEKDAY,CONVERT(DATETIME,CONVERT(VARCHAR(6),@Date,112+ '01')) - 1= 1 THEN 
(
DATEPART(DAY@Date- (7 - (DATEPART(WEEKDAY,CONVERT(DATETIME,CONVERT(VARCHAR(6),@Date,112+ '01')) - 1+ 2)) / 7 + 
CASE WHEN DATEPART(DAY,@Date)  < (7 - (DATEPART(WEEKDAY,CONVERT(DATETIME,CONVERT(VARCHAR(6),@Date,112+ '01')) - 1+ 2THEN 0 ELSE 1 END
ELSE DATEPART(DAY@Date/ 7 + 1 END AS 'WeekOfMonth'

 

posted on 2009-06-03 17:24  think8848  阅读(2245)  评论(2编辑  收藏  举报