Welcome to MSDN Blogs Sign in | Join | Help

SYSK 234: WeekDiff = Number of Weeks (full + partial) Between Two Dates

If you need to find out the number of weeks in a month, or the number of weeks between two given dates, and you need to includes partial weeks, not just full weeks as done by the T-SQL datediff(wk, d1, d2) function, then the code snippet below should get you started.

 

NOTE:  To make it a bit more flexible, you can add an argument (firstDayOfWeek) that the caller would need to pass in, instead of assuming that it’s Sunday, as in the code below.

 

private int WeekDiff(DateTime d1, DateTime d2)

{

    int result = 0;

 

    // Get first full week

    DateTime firstDayOfFirstFullWeek = d1;

    if (d1.DayOfWeek != DayOfWeek.Sunday)

    {

        result += 1;

        firstDayOfFirstFullWeek = d1.AddDays((7 - (int)d1.DayOfWeek));

    }

 

    // Get last full week

    DateTime lastDayOfLastFullWeek = d2;

    if (d2.DayOfWeek != DayOfWeek.Saturday)

    {

        result += 1;

        lastDayOfLastFullWeek = d2.AddDays(-(int)d2.DayOfWeek - 1);

    }

 

    // Add number of full weeks

    result += (lastDayOfLastFullWeek.Day - firstDayOfFirstFullWeek.Day + 1) / 7;

   

 

    return result;

}

 

 

Published Monday, November 06, 2006 7:10 AM by irenak

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker