How do I calculate the week number given a date?

2019-01-03 06:03发布

If I have a date, how do I calculate the week number for that date within that year?

For example, in 2008, January 1st to January 6th are in week 1 and January 7th to the 13th are in week 2, so if my date was January 10th 2008, my week number would be 2.

An algorithm would be great to get me started and sample code would also help - I'm developing in C++ on Windows.

Related:

Getting week number off a date in MS SQL Server 2005?

14条回答
看我几分像从前
2楼-- · 2019-01-03 07:03
public int GetWeekOfYear(DateTime todayDate)
{
    int days = todayDate.DayOfYear;
    float result = days / 7;
    result=result+1;
    Response.Write(result.ToString());
    return Convert.ToInt32(result);
}

Just pass the current date as the parameter to this function. Then you will get the current week number. Hope it solves ur problem. Any suggestions are greatly welcome.

查看更多
戒情不戒烟
3楼-- · 2019-01-03 07:04

Sorry, i'm new here and cant comment on the answer itself but the pseudo code from the answer with the checkmark isnt compeltey correct.

Pseudocode:

int julian = getDayOfYear(myDate)  // Jan 1 = 1, Jan 2 = 2, etc...
int dow = getDayOfWeek(myDate)     // Sun = 0, Mon = 1, etc...
int dowJan1 = getDayOfWeek("1/1/" + thisYear)   // find out first of year's day
int weekNum = (julian / 7) + 1     // Get our week#
if (dow < dowJan1)                 // adjust for being after Saturday of week #1
    ++weekNum;
return (weekNum)

you should not look for the "first of year's day", but for the last day of last year.

getDayOfWeek("12/31/" + thisYear-1)

would be correct instead of

getDayOfWeek("1/1/" + thisYear) 

If you don't do this, the last weekday of last year (like Monday) would always be one week ahead.

查看更多
登录 后发表回答