Get the correct week number of a given date












172















I have Googled a lot and found a lot of solutions, but none of them give me the correct week number for the 2012-12-31. Even the example on MSDN (link) fails.



2012-12-31 is Monday, therefore it should be Week 1, but every method I tried gives me 53. Here are some of the methods, that I have tried:



From the MDSN Library:



DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar cal = dfi.Calendar;

return cal.GetWeekOfYear(date, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);


Solution 2:



return new GregorianCalendar(GregorianCalendarTypes.Localized).GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);


Solution 3:



CultureInfo ciCurr = CultureInfo.CurrentCulture;
int weekNum = ciCurr.Calendar.GetWeekOfYear(dtPassed, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return weekNum;


Update



The following method actually returns 1 when date is 2012-12-31. In other words, my problem was that my methods were not following the ISO-8601 standard.



// This presumes that weeks start with Monday.
// Week 1 is the 1st week of the year with a Thursday in it.
public static int GetIso8601WeekOfYear(DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}

// Return the week of our adjusted day
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}









share|improve this question




















  • 4





    How is week 1 at the end of the year? I mean, I see where you get it. But 53 makes sense to me.

    – benjer3
    Jun 22 '12 at 10:47













  • In my code snippets I get the CultureInfo and stuff. I thought my program knows by then what calender I am using. (Here in Germany the 31st of December 2012 is in week 1 of 2013)

    – Amberlamps
    Jun 22 '12 at 11:19











  • This code doesn't work quite as it should try dates 31-dec-2016 for example or 1-jan-2016

    – cavej03
    Mar 24 '16 at 1:30











  • @cavej03 31-dec-2016 is week 52 and the GetIso8601WeekOfYear returns 52 so i guess it works correctly.

    – Muflix
    Dec 17 '16 at 19:25
















172















I have Googled a lot and found a lot of solutions, but none of them give me the correct week number for the 2012-12-31. Even the example on MSDN (link) fails.



2012-12-31 is Monday, therefore it should be Week 1, but every method I tried gives me 53. Here are some of the methods, that I have tried:



From the MDSN Library:



DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar cal = dfi.Calendar;

return cal.GetWeekOfYear(date, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);


Solution 2:



return new GregorianCalendar(GregorianCalendarTypes.Localized).GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);


Solution 3:



CultureInfo ciCurr = CultureInfo.CurrentCulture;
int weekNum = ciCurr.Calendar.GetWeekOfYear(dtPassed, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return weekNum;


Update



The following method actually returns 1 when date is 2012-12-31. In other words, my problem was that my methods were not following the ISO-8601 standard.



// This presumes that weeks start with Monday.
// Week 1 is the 1st week of the year with a Thursday in it.
public static int GetIso8601WeekOfYear(DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}

// Return the week of our adjusted day
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}









share|improve this question




















  • 4





    How is week 1 at the end of the year? I mean, I see where you get it. But 53 makes sense to me.

    – benjer3
    Jun 22 '12 at 10:47













  • In my code snippets I get the CultureInfo and stuff. I thought my program knows by then what calender I am using. (Here in Germany the 31st of December 2012 is in week 1 of 2013)

    – Amberlamps
    Jun 22 '12 at 11:19











  • This code doesn't work quite as it should try dates 31-dec-2016 for example or 1-jan-2016

    – cavej03
    Mar 24 '16 at 1:30











  • @cavej03 31-dec-2016 is week 52 and the GetIso8601WeekOfYear returns 52 so i guess it works correctly.

    – Muflix
    Dec 17 '16 at 19:25














172












172








172


35






I have Googled a lot and found a lot of solutions, but none of them give me the correct week number for the 2012-12-31. Even the example on MSDN (link) fails.



2012-12-31 is Monday, therefore it should be Week 1, but every method I tried gives me 53. Here are some of the methods, that I have tried:



From the MDSN Library:



DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar cal = dfi.Calendar;

return cal.GetWeekOfYear(date, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);


Solution 2:



return new GregorianCalendar(GregorianCalendarTypes.Localized).GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);


Solution 3:



CultureInfo ciCurr = CultureInfo.CurrentCulture;
int weekNum = ciCurr.Calendar.GetWeekOfYear(dtPassed, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return weekNum;


Update



The following method actually returns 1 when date is 2012-12-31. In other words, my problem was that my methods were not following the ISO-8601 standard.



// This presumes that weeks start with Monday.
// Week 1 is the 1st week of the year with a Thursday in it.
public static int GetIso8601WeekOfYear(DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}

// Return the week of our adjusted day
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}









share|improve this question
















I have Googled a lot and found a lot of solutions, but none of them give me the correct week number for the 2012-12-31. Even the example on MSDN (link) fails.



2012-12-31 is Monday, therefore it should be Week 1, but every method I tried gives me 53. Here are some of the methods, that I have tried:



From the MDSN Library:



DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar cal = dfi.Calendar;

return cal.GetWeekOfYear(date, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);


Solution 2:



return new GregorianCalendar(GregorianCalendarTypes.Localized).GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);


Solution 3:



CultureInfo ciCurr = CultureInfo.CurrentCulture;
int weekNum = ciCurr.Calendar.GetWeekOfYear(dtPassed, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return weekNum;


Update



The following method actually returns 1 when date is 2012-12-31. In other words, my problem was that my methods were not following the ISO-8601 standard.



// This presumes that weeks start with Monday.
// Week 1 is the 1st week of the year with a Thursday in it.
public static int GetIso8601WeekOfYear(DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}

// Return the week of our adjusted day
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}






c# asp.net .net date






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 13 '13 at 14:46









Stefano Altieri

3,91911534




3,91911534










asked Jun 22 '12 at 10:43









AmberlampsAmberlamps

19.5k43043




19.5k43043








  • 4





    How is week 1 at the end of the year? I mean, I see where you get it. But 53 makes sense to me.

    – benjer3
    Jun 22 '12 at 10:47













  • In my code snippets I get the CultureInfo and stuff. I thought my program knows by then what calender I am using. (Here in Germany the 31st of December 2012 is in week 1 of 2013)

    – Amberlamps
    Jun 22 '12 at 11:19











  • This code doesn't work quite as it should try dates 31-dec-2016 for example or 1-jan-2016

    – cavej03
    Mar 24 '16 at 1:30











  • @cavej03 31-dec-2016 is week 52 and the GetIso8601WeekOfYear returns 52 so i guess it works correctly.

    – Muflix
    Dec 17 '16 at 19:25














  • 4





    How is week 1 at the end of the year? I mean, I see where you get it. But 53 makes sense to me.

    – benjer3
    Jun 22 '12 at 10:47













  • In my code snippets I get the CultureInfo and stuff. I thought my program knows by then what calender I am using. (Here in Germany the 31st of December 2012 is in week 1 of 2013)

    – Amberlamps
    Jun 22 '12 at 11:19











  • This code doesn't work quite as it should try dates 31-dec-2016 for example or 1-jan-2016

    – cavej03
    Mar 24 '16 at 1:30











  • @cavej03 31-dec-2016 is week 52 and the GetIso8601WeekOfYear returns 52 so i guess it works correctly.

    – Muflix
    Dec 17 '16 at 19:25








4




4





How is week 1 at the end of the year? I mean, I see where you get it. But 53 makes sense to me.

– benjer3
Jun 22 '12 at 10:47







How is week 1 at the end of the year? I mean, I see where you get it. But 53 makes sense to me.

– benjer3
Jun 22 '12 at 10:47















In my code snippets I get the CultureInfo and stuff. I thought my program knows by then what calender I am using. (Here in Germany the 31st of December 2012 is in week 1 of 2013)

– Amberlamps
Jun 22 '12 at 11:19





In my code snippets I get the CultureInfo and stuff. I thought my program knows by then what calender I am using. (Here in Germany the 31st of December 2012 is in week 1 of 2013)

– Amberlamps
Jun 22 '12 at 11:19













This code doesn't work quite as it should try dates 31-dec-2016 for example or 1-jan-2016

– cavej03
Mar 24 '16 at 1:30





This code doesn't work quite as it should try dates 31-dec-2016 for example or 1-jan-2016

– cavej03
Mar 24 '16 at 1:30













@cavej03 31-dec-2016 is week 52 and the GetIso8601WeekOfYear returns 52 so i guess it works correctly.

– Muflix
Dec 17 '16 at 19:25





@cavej03 31-dec-2016 is week 52 and the GetIso8601WeekOfYear returns 52 so i guess it works correctly.

– Muflix
Dec 17 '16 at 19:25












11 Answers
11






active

oldest

votes


















251














As noted in this MSDN page there is a slight difference between ISO8601 week and .Net week numbering.



You can refer to this article in MSDN Blog for a better explanation: "ISO 8601 Week of Year format in Microsoft .Net"



Simply put, .Net allow weeks to be split across years while the ISO standard does not.
In the article there is also a simple function to get the correct ISO 8601 week number for the last week of the year.



Update The following method actually returns 1 for 2012-12-31 which is correct in ISO 8601 (e.g. Germany).



// This presumes that weeks start with Monday.
// Week 1 is the 1st week of the year with a Thursday in it.
public static int GetIso8601WeekOfYear(DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}

// Return the week of our adjusted day
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}





share|improve this answer





















  • 1





    @il_guru What if I wish the week starts with sunday?? Do i replace all "Monday" with "Sunday"??

    – User2012384
    Mar 17 '16 at 8:12






  • 2





    @User2012384 fyi, if you want to follow the ISO8601 standard the firstDayOfWeek should always be Monday.

    – Starceaker
    Apr 5 '16 at 9:07






  • 1





    @Starceaker you are wrong, ISO8601 states that the first week of the year is "the week with the year's first Thursday in it (the formal ISO definition)"

    – il_guru
    Apr 5 '16 at 10:23






  • 1





    If you look the second link (ISO 8601 Week of Year format in Microsoft .Net), you could find the answer to your question directly from Microsoft. An example is Monday 31/12/2007: with the .Net function it will return week number 53 of 2007 while for the ISO standard it is week number 1 of 2008

    – il_guru
    Apr 11 '16 at 13:22








  • 1





    I've manually verified this to be correct for years 2012 to 2018 (assuming that epochconverter.com is correct). We should all rejoice this year that week 1 of 2018 actually started on the first of January for once!

    – Aidan
    Oct 21 '18 at 10:39



















28














There can be more than 52 weeks in a year. Each year has 52 full weeks + 1 or +2 (leap year) days extra. They make up for a 53th week.




  • 52 weeks * 7days = 364 days.


So for each year you have at least one an extra day. Two for leap years. Are these extra days counted as separate weeks of their own?



How many weeks there are really depends on the starting day of your week. Let's consider this for 2012.




  • US (Sunday -> Saturday): 52 weeks + one short 2 day week for 2012-12-30 & 2012-12-31. This results in a total of 53 weeks. Last two days of this year (Sunday + Monday) make up their own short week.


Check your current Culture's settings to see what it uses as the first day of the week.



As you see it's normal to get 53 as a result.




  • Europe (Monday -> Sunday): January 2dn (2012-1-2) is the first monday, so this is the first day of the first week. Ask the week number for the 1st of January and you'll get back 52 as it is considered part of 2011 last's week.


It's even possible to have a 54th week. Happens every 28 years when the 1st of January and the 31st of December are treated as separate weeks. It must be a leap year too.



For example, the year 2000 had 54 weeks. January 1st (sat) was the first one week day, and 31st December (sun) was the second one week day.



var d = new DateTime(2012, 12, 31);
CultureInfo cul = CultureInfo.CurrentCulture;

var firstDayWeek = cul.Calendar.GetWeekOfYear(
d,
CalendarWeekRule.FirstDay,
DayOfWeek.Monday);

int weekNum = cul.Calendar.GetWeekOfYear(
d,
CalendarWeekRule.FirstDay,
DayOfWeek.Monday);

int year = weekNum == 52 && d.Month == 1 ? d.Year - 1 : d.Year;
Console.WriteLine("Year: {0} Week: {1}", year, weekNum);


Prints out: Year: 2012 Week: 54



Change CalendarWeekRule in the above example to FirstFullWeek or FirstFourDayWeek and you'll get back 53. Let's keep the start day on Monday since we are dealing with Germany.



So week 53 starts on monday 2012-12-31, lasts one day and then stops.



53 is the correct answer. Change the Culture to germany if want to to try it.



CultureInfo cul = CultureInfo.GetCultureInfo("de-DE");





share|improve this answer


























  • I know that it is possible that there are 53 weeks. But when you have sunday (12/30) and monday (12/31), don´t you count thuesday (01/01) also as part of the 53th week in the US?

    – Amberlamps
    Jun 22 '12 at 11:09











  • I have never seen a 54th week!

    – Amberlamps
    Jun 22 '12 at 11:09











  • Certain fiscal software packages do have them.

    – Christophe Geers
    Jun 22 '12 at 11:11






  • 1





    @TimSchmelter nice example, included it in the post

    – Christophe Geers
    Jun 22 '12 at 11:21






  • 1





    +1 for your deep thoughts on the issue, but the code snippet in the blog entry provided in a different answer actually solved my problem.

    – Amberlamps
    Jun 22 '12 at 11:35





















13














This is the way:



public int GetWeekNumber()
{
CultureInfo ciCurr = CultureInfo.CurrentCulture;
int weekNum = ciCurr.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return weekNum;
}


Most important for is the CalendarWeekRule parameter.



See here:
https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=IT-IT&k=k(System.Globalization.CalendarWeekRule);k(TargetFrameworkMoniker-.NETFramework






share|improve this answer
























  • "Several people have noticed that Calendar.GetWeekOfYear() is almost like the ISO 8601 week when passed CalendarWeekRule.FirstFourDayWeek and DayOfWeek.Monday, however it is a little bit different. Specifically ISO 8601 always has 7 day weeks. " blogs.msdn.microsoft.com/shawnste/2006/01/24/…

    – Juha Palomäki
    Jan 31 '17 at 22:45



















9














I'm going to play Necromancer here :-)



Since there doesn't seem to be a .Net-culture that yields the correct ISO-8601 week number, I'd rather bypass the built-in week determination altogether, and do the calculation manually, instead of attempting to correct a partially correct result.



What I ended up with is the following extension method:



/// <summary>
/// Converts a date to a week number.
/// ISO 8601 week 1 is the week that contains the first Thursday that year.
/// </summary>
public static int ToIso8601Weeknumber(this DateTime date)
{
var thursday = date.AddDays(3 - date.DayOfWeek.DayOffset());
return (thursday.DayOfYear - 1) / 7 + 1;
}

/// <summary>
/// Converts a week number to a date.
/// Note: Week 1 of a year may start in the previous year.
/// ISO 8601 week 1 is the week that contains the first Thursday that year, so
/// if December 28 is a Monday, December 31 is a Thursday,
/// and week 1 starts January 4.
/// If December 28 is a later day in the week, week 1 starts earlier.
/// If December 28 is a Sunday, it is in the same week as Thursday January 1.
/// </summary>
public static DateTime FromIso8601Weeknumber(int weekNumber, int? year = null, DayOfWeek day = DayOfWeek.Monday)
{
var dec28 = new DateTime((year ?? DateTime.Today.Year) - 1, 12, 28);
var monday = dec28.AddDays(7 * weekNumber - dec28.DayOfWeek.DayOffset());
return monday.AddDays(day.DayOffset());
}

/// <summary>
/// Iso8601 weeks start on Monday. This returns 0 for Monday.
/// </summary>
private static int DayOffset(this DayOfWeek weekDay)
{
return ((int)weekDay + 6) % 7;
}




First of all, ((int)date.DayOfWeek + 6) % 7) determines the weekday number, 0=monday, 6=sunday.



date.AddDays(-((int)date.DayOfWeek + 6) % 7) determines the date of the monday preceiding the requested week number.



Three days later is the target thursday, which determines what year the week is in.



If you divide the (zero based) day-number within the year by seven (round down), you get the (zero based) week number in the year.



In c#, integer calculation results are round down implicitly.






share|improve this answer

































    4














    Good news! A pull request adding System.Globalization.ISOWeek to .NET Core was just merged and is currently slated for the 3.0 release. Hopefully it will propagate to the other .NET platforms in a not-too-distant future.



    The type has the following signature, which should cover most ISO week needs:



    namespace System.Globalization
    {
    public static class ISOWeek
    {
    public static int GetWeekOfYear(DateTime date);
    public static int GetWeeksInYear(int year);
    public static int GetYear(DateTime date);
    public static DateTime GetYearEnd(int year);
    public static DateTime GetYearStart(int year);
    public static DateTime ToDateTime(int year, int week, DayOfWeek dayOfWeek);
    }
    }


    You can find the source code here.






    share|improve this answer
























    • Any idea when v 3.0 will be released?

      – Jacques
      Aug 1 '18 at 8:25











    • "We are planning on releasing a first preview of .NET Core 3 later this year and the final version in 2019." (from the roadmap blog post)

      – khellang
      Aug 1 '18 at 8:41








    • 1





      But based on the roadmap, there should be a 2.2 release this year as well, which should include these APIs.

      – khellang
      Aug 1 '18 at 8:44



















    3














    C# to Powershell port from code above from il_guru:



    function GetWeekOfYear([datetime] $inputDate)
    {
    $day = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetDayOfWeek($inputDate)
    if (($day -ge [System.DayOfWeek]::Monday) -and ($day -le [System.DayOfWeek]::Wednesday))
    {
    $inputDate = $inputDate.AddDays(3)
    }

    # Return the week of our adjusted day
    $weekofYear = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetWeekOfYear($inputDate, [System.Globalization.CalendarWeekRule]::FirstFourDayWeek, [System.DayOfWeek]::Monday)
    return $weekofYear
    }





    share|improve this answer





















    • 1





      Could you explain your code? Code-only answers are generally not acceptable on StackOverflow, and as such are liable to be deleted.

      – Wai Ha Lee
      Oct 1 '15 at 0:20











    • @Wai Ha Lee the code is already explained. See post above from il_guru. I ported his code to powershell, so other people can use it in powershell because there are no good solution in powershell so far.

      – Rainer
      Oct 7 '15 at 11:29











    • If that's what you did, you should credit the original author in the answer itself. The answer you ported has better comments which you have presumably removed. Also, this isn't an answer to the question since the question did not mention PowerShell.

      – Wai Ha Lee
      Oct 7 '15 at 11:32






    • 1





      I did now @Wai Ha Lee. The question is already marked as answered, so this would be the same solution written in an other language. I made a favour for people, which are looking for an solution in Powershell language (I was looking hard for an solution in Powershell, but what I found was a solution in C#). The idea remains the same and the author gets the credit for it.

      – Rainer
      Oct 7 '15 at 11:39



















    2














    The easiest way to determine the week number ISO 8601 style using c# and the DateTime class.



    Ask this: the how-many-eth thursday of the year is the thursday of this week.
    The answer equals the wanted week number.



    var dayOfWeek = (int)moment.DayOfWeek;
    // Make monday the first day of the week
    if (--dayOfWeek < 0)
    dayOfWeek = 6;
    // The whole nr of weeks before this thursday plus one is the week number
    var weekNumber = (moment.AddDays(3 - dayOfWeek).DayOfYear - 1) / 7 + 1;





    share|improve this answer































      1














      var cultureInfo = CultureInfo.CurrentCulture;
      var calendar = cultureInfo.Calendar;

      var calendarWeekRule = cultureInfo.DateTimeFormat.CalendarWeekRule;
      var firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
      var lastDayOfWeek = cultureInfo.LCID == 1033 //En-us
      ? DayOfWeek.Saturday
      : DayOfWeek.Sunday;

      var lastDayOfYear = new DateTime(date.Year, 12, 31);

      var weekNumber = calendar.GetWeekOfYear(date, calendarWeekRule, firstDayOfWeek);

      //Check if this is the last week in the year and it doesn`t occupy the whole week
      return weekNumber == 53 && lastDayOfYear.DayOfWeek != lastDayOfWeek
      ? 1
      : weekNumber;


      It works well both for US and Russian cultures. ISO 8601 also will be correct, `cause Russian week starts at Monday.






      share|improve this answer

































        0














        The question is: How do you define if a week is in 2012 or in 2013?
        Your supposition, I guess, is that since 6 days of the week are in 2013, this week should be marked as the first week of 2013.



        Not sure if this is the right way to go.
        That week started on 2012 (On monday 31th Dec), so it should be marked as the last week of 2012, therefore it should be the 53rd of 2012. The first week of 2013 should start on monday the 7th.



        Now, you can handle the particular case of edge weeks (first and last week of the year) using the day of week information. It all depends on your logic.






        share|improve this answer


























        • Okay, I can see your point. The thing is when I use 2013/01/07 in any of my methods, it say week 2. So, 2012/12/31 is week 53 and 2013/01/07 is week 2. You might think there is no week 1 of 2013. But when I try 2013/01/01 it says week 1.

          – Amberlamps
          Jun 22 '12 at 11:11





















        0














          DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
        DateTime date1 = new DateTime(2011, 1, 1);
        Calendar cal = dfi.Calendar;

        Console.WriteLine("{0:d}: Week {1} ({2})", date1,
        cal.GetWeekOfYear(date1, dfi.CalendarWeekRule,
        dfi.FirstDayOfWeek),
        cal.ToString().Substring(cal.ToString().LastIndexOf(".") + 1));





        share|improve this answer































          -1














          A year has 52 weeks and 1 day or 2 in case of a lap year (52 x 7 = 364). 2012-12-31 would be week 53, a week that would only have 2 days because 2012 is a lap year.






          share|improve this answer
























          • This is incorrect. The first day of the week of the year may fall on any day of the week, depending on how you count the weeks, the year may have a 54th week.

            – krowe2
            Jul 17 '18 at 20:22













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11154673%2fget-the-correct-week-number-of-a-given-date%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          11 Answers
          11






          active

          oldest

          votes








          11 Answers
          11






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          251














          As noted in this MSDN page there is a slight difference between ISO8601 week and .Net week numbering.



          You can refer to this article in MSDN Blog for a better explanation: "ISO 8601 Week of Year format in Microsoft .Net"



          Simply put, .Net allow weeks to be split across years while the ISO standard does not.
          In the article there is also a simple function to get the correct ISO 8601 week number for the last week of the year.



          Update The following method actually returns 1 for 2012-12-31 which is correct in ISO 8601 (e.g. Germany).



          // This presumes that weeks start with Monday.
          // Week 1 is the 1st week of the year with a Thursday in it.
          public static int GetIso8601WeekOfYear(DateTime time)
          {
          // Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
          // be the same week# as whatever Thursday, Friday or Saturday are,
          // and we always get those right
          DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
          if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
          {
          time = time.AddDays(3);
          }

          // Return the week of our adjusted day
          return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
          }





          share|improve this answer





















          • 1





            @il_guru What if I wish the week starts with sunday?? Do i replace all "Monday" with "Sunday"??

            – User2012384
            Mar 17 '16 at 8:12






          • 2





            @User2012384 fyi, if you want to follow the ISO8601 standard the firstDayOfWeek should always be Monday.

            – Starceaker
            Apr 5 '16 at 9:07






          • 1





            @Starceaker you are wrong, ISO8601 states that the first week of the year is "the week with the year's first Thursday in it (the formal ISO definition)"

            – il_guru
            Apr 5 '16 at 10:23






          • 1





            If you look the second link (ISO 8601 Week of Year format in Microsoft .Net), you could find the answer to your question directly from Microsoft. An example is Monday 31/12/2007: with the .Net function it will return week number 53 of 2007 while for the ISO standard it is week number 1 of 2008

            – il_guru
            Apr 11 '16 at 13:22








          • 1





            I've manually verified this to be correct for years 2012 to 2018 (assuming that epochconverter.com is correct). We should all rejoice this year that week 1 of 2018 actually started on the first of January for once!

            – Aidan
            Oct 21 '18 at 10:39
















          251














          As noted in this MSDN page there is a slight difference between ISO8601 week and .Net week numbering.



          You can refer to this article in MSDN Blog for a better explanation: "ISO 8601 Week of Year format in Microsoft .Net"



          Simply put, .Net allow weeks to be split across years while the ISO standard does not.
          In the article there is also a simple function to get the correct ISO 8601 week number for the last week of the year.



          Update The following method actually returns 1 for 2012-12-31 which is correct in ISO 8601 (e.g. Germany).



          // This presumes that weeks start with Monday.
          // Week 1 is the 1st week of the year with a Thursday in it.
          public static int GetIso8601WeekOfYear(DateTime time)
          {
          // Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
          // be the same week# as whatever Thursday, Friday or Saturday are,
          // and we always get those right
          DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
          if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
          {
          time = time.AddDays(3);
          }

          // Return the week of our adjusted day
          return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
          }





          share|improve this answer





















          • 1





            @il_guru What if I wish the week starts with sunday?? Do i replace all "Monday" with "Sunday"??

            – User2012384
            Mar 17 '16 at 8:12






          • 2





            @User2012384 fyi, if you want to follow the ISO8601 standard the firstDayOfWeek should always be Monday.

            – Starceaker
            Apr 5 '16 at 9:07






          • 1





            @Starceaker you are wrong, ISO8601 states that the first week of the year is "the week with the year's first Thursday in it (the formal ISO definition)"

            – il_guru
            Apr 5 '16 at 10:23






          • 1





            If you look the second link (ISO 8601 Week of Year format in Microsoft .Net), you could find the answer to your question directly from Microsoft. An example is Monday 31/12/2007: with the .Net function it will return week number 53 of 2007 while for the ISO standard it is week number 1 of 2008

            – il_guru
            Apr 11 '16 at 13:22








          • 1





            I've manually verified this to be correct for years 2012 to 2018 (assuming that epochconverter.com is correct). We should all rejoice this year that week 1 of 2018 actually started on the first of January for once!

            – Aidan
            Oct 21 '18 at 10:39














          251












          251








          251







          As noted in this MSDN page there is a slight difference between ISO8601 week and .Net week numbering.



          You can refer to this article in MSDN Blog for a better explanation: "ISO 8601 Week of Year format in Microsoft .Net"



          Simply put, .Net allow weeks to be split across years while the ISO standard does not.
          In the article there is also a simple function to get the correct ISO 8601 week number for the last week of the year.



          Update The following method actually returns 1 for 2012-12-31 which is correct in ISO 8601 (e.g. Germany).



          // This presumes that weeks start with Monday.
          // Week 1 is the 1st week of the year with a Thursday in it.
          public static int GetIso8601WeekOfYear(DateTime time)
          {
          // Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
          // be the same week# as whatever Thursday, Friday or Saturday are,
          // and we always get those right
          DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
          if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
          {
          time = time.AddDays(3);
          }

          // Return the week of our adjusted day
          return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
          }





          share|improve this answer















          As noted in this MSDN page there is a slight difference between ISO8601 week and .Net week numbering.



          You can refer to this article in MSDN Blog for a better explanation: "ISO 8601 Week of Year format in Microsoft .Net"



          Simply put, .Net allow weeks to be split across years while the ISO standard does not.
          In the article there is also a simple function to get the correct ISO 8601 week number for the last week of the year.



          Update The following method actually returns 1 for 2012-12-31 which is correct in ISO 8601 (e.g. Germany).



          // This presumes that weeks start with Monday.
          // Week 1 is the 1st week of the year with a Thursday in it.
          public static int GetIso8601WeekOfYear(DateTime time)
          {
          // Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
          // be the same week# as whatever Thursday, Friday or Saturday are,
          // and we always get those right
          DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
          if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
          {
          time = time.AddDays(3);
          }

          // Return the week of our adjusted day
          return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Apr 15 '13 at 13:37









          Dzienny

          2,59711627




          2,59711627










          answered Jun 22 '12 at 11:13









          il_guruil_guru

          6,44523347




          6,44523347








          • 1





            @il_guru What if I wish the week starts with sunday?? Do i replace all "Monday" with "Sunday"??

            – User2012384
            Mar 17 '16 at 8:12






          • 2





            @User2012384 fyi, if you want to follow the ISO8601 standard the firstDayOfWeek should always be Monday.

            – Starceaker
            Apr 5 '16 at 9:07






          • 1





            @Starceaker you are wrong, ISO8601 states that the first week of the year is "the week with the year's first Thursday in it (the formal ISO definition)"

            – il_guru
            Apr 5 '16 at 10:23






          • 1





            If you look the second link (ISO 8601 Week of Year format in Microsoft .Net), you could find the answer to your question directly from Microsoft. An example is Monday 31/12/2007: with the .Net function it will return week number 53 of 2007 while for the ISO standard it is week number 1 of 2008

            – il_guru
            Apr 11 '16 at 13:22








          • 1





            I've manually verified this to be correct for years 2012 to 2018 (assuming that epochconverter.com is correct). We should all rejoice this year that week 1 of 2018 actually started on the first of January for once!

            – Aidan
            Oct 21 '18 at 10:39














          • 1





            @il_guru What if I wish the week starts with sunday?? Do i replace all "Monday" with "Sunday"??

            – User2012384
            Mar 17 '16 at 8:12






          • 2





            @User2012384 fyi, if you want to follow the ISO8601 standard the firstDayOfWeek should always be Monday.

            – Starceaker
            Apr 5 '16 at 9:07






          • 1





            @Starceaker you are wrong, ISO8601 states that the first week of the year is "the week with the year's first Thursday in it (the formal ISO definition)"

            – il_guru
            Apr 5 '16 at 10:23






          • 1





            If you look the second link (ISO 8601 Week of Year format in Microsoft .Net), you could find the answer to your question directly from Microsoft. An example is Monday 31/12/2007: with the .Net function it will return week number 53 of 2007 while for the ISO standard it is week number 1 of 2008

            – il_guru
            Apr 11 '16 at 13:22








          • 1





            I've manually verified this to be correct for years 2012 to 2018 (assuming that epochconverter.com is correct). We should all rejoice this year that week 1 of 2018 actually started on the first of January for once!

            – Aidan
            Oct 21 '18 at 10:39








          1




          1





          @il_guru What if I wish the week starts with sunday?? Do i replace all "Monday" with "Sunday"??

          – User2012384
          Mar 17 '16 at 8:12





          @il_guru What if I wish the week starts with sunday?? Do i replace all "Monday" with "Sunday"??

          – User2012384
          Mar 17 '16 at 8:12




          2




          2





          @User2012384 fyi, if you want to follow the ISO8601 standard the firstDayOfWeek should always be Monday.

          – Starceaker
          Apr 5 '16 at 9:07





          @User2012384 fyi, if you want to follow the ISO8601 standard the firstDayOfWeek should always be Monday.

          – Starceaker
          Apr 5 '16 at 9:07




          1




          1





          @Starceaker you are wrong, ISO8601 states that the first week of the year is "the week with the year's first Thursday in it (the formal ISO definition)"

          – il_guru
          Apr 5 '16 at 10:23





          @Starceaker you are wrong, ISO8601 states that the first week of the year is "the week with the year's first Thursday in it (the formal ISO definition)"

          – il_guru
          Apr 5 '16 at 10:23




          1




          1





          If you look the second link (ISO 8601 Week of Year format in Microsoft .Net), you could find the answer to your question directly from Microsoft. An example is Monday 31/12/2007: with the .Net function it will return week number 53 of 2007 while for the ISO standard it is week number 1 of 2008

          – il_guru
          Apr 11 '16 at 13:22







          If you look the second link (ISO 8601 Week of Year format in Microsoft .Net), you could find the answer to your question directly from Microsoft. An example is Monday 31/12/2007: with the .Net function it will return week number 53 of 2007 while for the ISO standard it is week number 1 of 2008

          – il_guru
          Apr 11 '16 at 13:22






          1




          1





          I've manually verified this to be correct for years 2012 to 2018 (assuming that epochconverter.com is correct). We should all rejoice this year that week 1 of 2018 actually started on the first of January for once!

          – Aidan
          Oct 21 '18 at 10:39





          I've manually verified this to be correct for years 2012 to 2018 (assuming that epochconverter.com is correct). We should all rejoice this year that week 1 of 2018 actually started on the first of January for once!

          – Aidan
          Oct 21 '18 at 10:39













          28














          There can be more than 52 weeks in a year. Each year has 52 full weeks + 1 or +2 (leap year) days extra. They make up for a 53th week.




          • 52 weeks * 7days = 364 days.


          So for each year you have at least one an extra day. Two for leap years. Are these extra days counted as separate weeks of their own?



          How many weeks there are really depends on the starting day of your week. Let's consider this for 2012.




          • US (Sunday -> Saturday): 52 weeks + one short 2 day week for 2012-12-30 & 2012-12-31. This results in a total of 53 weeks. Last two days of this year (Sunday + Monday) make up their own short week.


          Check your current Culture's settings to see what it uses as the first day of the week.



          As you see it's normal to get 53 as a result.




          • Europe (Monday -> Sunday): January 2dn (2012-1-2) is the first monday, so this is the first day of the first week. Ask the week number for the 1st of January and you'll get back 52 as it is considered part of 2011 last's week.


          It's even possible to have a 54th week. Happens every 28 years when the 1st of January and the 31st of December are treated as separate weeks. It must be a leap year too.



          For example, the year 2000 had 54 weeks. January 1st (sat) was the first one week day, and 31st December (sun) was the second one week day.



          var d = new DateTime(2012, 12, 31);
          CultureInfo cul = CultureInfo.CurrentCulture;

          var firstDayWeek = cul.Calendar.GetWeekOfYear(
          d,
          CalendarWeekRule.FirstDay,
          DayOfWeek.Monday);

          int weekNum = cul.Calendar.GetWeekOfYear(
          d,
          CalendarWeekRule.FirstDay,
          DayOfWeek.Monday);

          int year = weekNum == 52 && d.Month == 1 ? d.Year - 1 : d.Year;
          Console.WriteLine("Year: {0} Week: {1}", year, weekNum);


          Prints out: Year: 2012 Week: 54



          Change CalendarWeekRule in the above example to FirstFullWeek or FirstFourDayWeek and you'll get back 53. Let's keep the start day on Monday since we are dealing with Germany.



          So week 53 starts on monday 2012-12-31, lasts one day and then stops.



          53 is the correct answer. Change the Culture to germany if want to to try it.



          CultureInfo cul = CultureInfo.GetCultureInfo("de-DE");





          share|improve this answer


























          • I know that it is possible that there are 53 weeks. But when you have sunday (12/30) and monday (12/31), don´t you count thuesday (01/01) also as part of the 53th week in the US?

            – Amberlamps
            Jun 22 '12 at 11:09











          • I have never seen a 54th week!

            – Amberlamps
            Jun 22 '12 at 11:09











          • Certain fiscal software packages do have them.

            – Christophe Geers
            Jun 22 '12 at 11:11






          • 1





            @TimSchmelter nice example, included it in the post

            – Christophe Geers
            Jun 22 '12 at 11:21






          • 1





            +1 for your deep thoughts on the issue, but the code snippet in the blog entry provided in a different answer actually solved my problem.

            – Amberlamps
            Jun 22 '12 at 11:35


















          28














          There can be more than 52 weeks in a year. Each year has 52 full weeks + 1 or +2 (leap year) days extra. They make up for a 53th week.




          • 52 weeks * 7days = 364 days.


          So for each year you have at least one an extra day. Two for leap years. Are these extra days counted as separate weeks of their own?



          How many weeks there are really depends on the starting day of your week. Let's consider this for 2012.




          • US (Sunday -> Saturday): 52 weeks + one short 2 day week for 2012-12-30 & 2012-12-31. This results in a total of 53 weeks. Last two days of this year (Sunday + Monday) make up their own short week.


          Check your current Culture's settings to see what it uses as the first day of the week.



          As you see it's normal to get 53 as a result.




          • Europe (Monday -> Sunday): January 2dn (2012-1-2) is the first monday, so this is the first day of the first week. Ask the week number for the 1st of January and you'll get back 52 as it is considered part of 2011 last's week.


          It's even possible to have a 54th week. Happens every 28 years when the 1st of January and the 31st of December are treated as separate weeks. It must be a leap year too.



          For example, the year 2000 had 54 weeks. January 1st (sat) was the first one week day, and 31st December (sun) was the second one week day.



          var d = new DateTime(2012, 12, 31);
          CultureInfo cul = CultureInfo.CurrentCulture;

          var firstDayWeek = cul.Calendar.GetWeekOfYear(
          d,
          CalendarWeekRule.FirstDay,
          DayOfWeek.Monday);

          int weekNum = cul.Calendar.GetWeekOfYear(
          d,
          CalendarWeekRule.FirstDay,
          DayOfWeek.Monday);

          int year = weekNum == 52 && d.Month == 1 ? d.Year - 1 : d.Year;
          Console.WriteLine("Year: {0} Week: {1}", year, weekNum);


          Prints out: Year: 2012 Week: 54



          Change CalendarWeekRule in the above example to FirstFullWeek or FirstFourDayWeek and you'll get back 53. Let's keep the start day on Monday since we are dealing with Germany.



          So week 53 starts on monday 2012-12-31, lasts one day and then stops.



          53 is the correct answer. Change the Culture to germany if want to to try it.



          CultureInfo cul = CultureInfo.GetCultureInfo("de-DE");





          share|improve this answer


























          • I know that it is possible that there are 53 weeks. But when you have sunday (12/30) and monday (12/31), don´t you count thuesday (01/01) also as part of the 53th week in the US?

            – Amberlamps
            Jun 22 '12 at 11:09











          • I have never seen a 54th week!

            – Amberlamps
            Jun 22 '12 at 11:09











          • Certain fiscal software packages do have them.

            – Christophe Geers
            Jun 22 '12 at 11:11






          • 1





            @TimSchmelter nice example, included it in the post

            – Christophe Geers
            Jun 22 '12 at 11:21






          • 1





            +1 for your deep thoughts on the issue, but the code snippet in the blog entry provided in a different answer actually solved my problem.

            – Amberlamps
            Jun 22 '12 at 11:35
















          28












          28








          28







          There can be more than 52 weeks in a year. Each year has 52 full weeks + 1 or +2 (leap year) days extra. They make up for a 53th week.




          • 52 weeks * 7days = 364 days.


          So for each year you have at least one an extra day. Two for leap years. Are these extra days counted as separate weeks of their own?



          How many weeks there are really depends on the starting day of your week. Let's consider this for 2012.




          • US (Sunday -> Saturday): 52 weeks + one short 2 day week for 2012-12-30 & 2012-12-31. This results in a total of 53 weeks. Last two days of this year (Sunday + Monday) make up their own short week.


          Check your current Culture's settings to see what it uses as the first day of the week.



          As you see it's normal to get 53 as a result.




          • Europe (Monday -> Sunday): January 2dn (2012-1-2) is the first monday, so this is the first day of the first week. Ask the week number for the 1st of January and you'll get back 52 as it is considered part of 2011 last's week.


          It's even possible to have a 54th week. Happens every 28 years when the 1st of January and the 31st of December are treated as separate weeks. It must be a leap year too.



          For example, the year 2000 had 54 weeks. January 1st (sat) was the first one week day, and 31st December (sun) was the second one week day.



          var d = new DateTime(2012, 12, 31);
          CultureInfo cul = CultureInfo.CurrentCulture;

          var firstDayWeek = cul.Calendar.GetWeekOfYear(
          d,
          CalendarWeekRule.FirstDay,
          DayOfWeek.Monday);

          int weekNum = cul.Calendar.GetWeekOfYear(
          d,
          CalendarWeekRule.FirstDay,
          DayOfWeek.Monday);

          int year = weekNum == 52 && d.Month == 1 ? d.Year - 1 : d.Year;
          Console.WriteLine("Year: {0} Week: {1}", year, weekNum);


          Prints out: Year: 2012 Week: 54



          Change CalendarWeekRule in the above example to FirstFullWeek or FirstFourDayWeek and you'll get back 53. Let's keep the start day on Monday since we are dealing with Germany.



          So week 53 starts on monday 2012-12-31, lasts one day and then stops.



          53 is the correct answer. Change the Culture to germany if want to to try it.



          CultureInfo cul = CultureInfo.GetCultureInfo("de-DE");





          share|improve this answer















          There can be more than 52 weeks in a year. Each year has 52 full weeks + 1 or +2 (leap year) days extra. They make up for a 53th week.




          • 52 weeks * 7days = 364 days.


          So for each year you have at least one an extra day. Two for leap years. Are these extra days counted as separate weeks of their own?



          How many weeks there are really depends on the starting day of your week. Let's consider this for 2012.




          • US (Sunday -> Saturday): 52 weeks + one short 2 day week for 2012-12-30 & 2012-12-31. This results in a total of 53 weeks. Last two days of this year (Sunday + Monday) make up their own short week.


          Check your current Culture's settings to see what it uses as the first day of the week.



          As you see it's normal to get 53 as a result.




          • Europe (Monday -> Sunday): January 2dn (2012-1-2) is the first monday, so this is the first day of the first week. Ask the week number for the 1st of January and you'll get back 52 as it is considered part of 2011 last's week.


          It's even possible to have a 54th week. Happens every 28 years when the 1st of January and the 31st of December are treated as separate weeks. It must be a leap year too.



          For example, the year 2000 had 54 weeks. January 1st (sat) was the first one week day, and 31st December (sun) was the second one week day.



          var d = new DateTime(2012, 12, 31);
          CultureInfo cul = CultureInfo.CurrentCulture;

          var firstDayWeek = cul.Calendar.GetWeekOfYear(
          d,
          CalendarWeekRule.FirstDay,
          DayOfWeek.Monday);

          int weekNum = cul.Calendar.GetWeekOfYear(
          d,
          CalendarWeekRule.FirstDay,
          DayOfWeek.Monday);

          int year = weekNum == 52 && d.Month == 1 ? d.Year - 1 : d.Year;
          Console.WriteLine("Year: {0} Week: {1}", year, weekNum);


          Prints out: Year: 2012 Week: 54



          Change CalendarWeekRule in the above example to FirstFullWeek or FirstFourDayWeek and you'll get back 53. Let's keep the start day on Monday since we are dealing with Germany.



          So week 53 starts on monday 2012-12-31, lasts one day and then stops.



          53 is the correct answer. Change the Culture to germany if want to to try it.



          CultureInfo cul = CultureInfo.GetCultureInfo("de-DE");






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Feb 16 '17 at 9:58









          Prashant Yadav

          3201418




          3201418










          answered Jun 22 '12 at 11:00









          Christophe GeersChristophe Geers

          6,58922342




          6,58922342













          • I know that it is possible that there are 53 weeks. But when you have sunday (12/30) and monday (12/31), don´t you count thuesday (01/01) also as part of the 53th week in the US?

            – Amberlamps
            Jun 22 '12 at 11:09











          • I have never seen a 54th week!

            – Amberlamps
            Jun 22 '12 at 11:09











          • Certain fiscal software packages do have them.

            – Christophe Geers
            Jun 22 '12 at 11:11






          • 1





            @TimSchmelter nice example, included it in the post

            – Christophe Geers
            Jun 22 '12 at 11:21






          • 1





            +1 for your deep thoughts on the issue, but the code snippet in the blog entry provided in a different answer actually solved my problem.

            – Amberlamps
            Jun 22 '12 at 11:35





















          • I know that it is possible that there are 53 weeks. But when you have sunday (12/30) and monday (12/31), don´t you count thuesday (01/01) also as part of the 53th week in the US?

            – Amberlamps
            Jun 22 '12 at 11:09











          • I have never seen a 54th week!

            – Amberlamps
            Jun 22 '12 at 11:09











          • Certain fiscal software packages do have them.

            – Christophe Geers
            Jun 22 '12 at 11:11






          • 1





            @TimSchmelter nice example, included it in the post

            – Christophe Geers
            Jun 22 '12 at 11:21






          • 1





            +1 for your deep thoughts on the issue, but the code snippet in the blog entry provided in a different answer actually solved my problem.

            – Amberlamps
            Jun 22 '12 at 11:35



















          I know that it is possible that there are 53 weeks. But when you have sunday (12/30) and monday (12/31), don´t you count thuesday (01/01) also as part of the 53th week in the US?

          – Amberlamps
          Jun 22 '12 at 11:09





          I know that it is possible that there are 53 weeks. But when you have sunday (12/30) and monday (12/31), don´t you count thuesday (01/01) also as part of the 53th week in the US?

          – Amberlamps
          Jun 22 '12 at 11:09













          I have never seen a 54th week!

          – Amberlamps
          Jun 22 '12 at 11:09





          I have never seen a 54th week!

          – Amberlamps
          Jun 22 '12 at 11:09













          Certain fiscal software packages do have them.

          – Christophe Geers
          Jun 22 '12 at 11:11





          Certain fiscal software packages do have them.

          – Christophe Geers
          Jun 22 '12 at 11:11




          1




          1





          @TimSchmelter nice example, included it in the post

          – Christophe Geers
          Jun 22 '12 at 11:21





          @TimSchmelter nice example, included it in the post

          – Christophe Geers
          Jun 22 '12 at 11:21




          1




          1





          +1 for your deep thoughts on the issue, but the code snippet in the blog entry provided in a different answer actually solved my problem.

          – Amberlamps
          Jun 22 '12 at 11:35







          +1 for your deep thoughts on the issue, but the code snippet in the blog entry provided in a different answer actually solved my problem.

          – Amberlamps
          Jun 22 '12 at 11:35













          13














          This is the way:



          public int GetWeekNumber()
          {
          CultureInfo ciCurr = CultureInfo.CurrentCulture;
          int weekNum = ciCurr.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
          return weekNum;
          }


          Most important for is the CalendarWeekRule parameter.



          See here:
          https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=IT-IT&k=k(System.Globalization.CalendarWeekRule);k(TargetFrameworkMoniker-.NETFramework






          share|improve this answer
























          • "Several people have noticed that Calendar.GetWeekOfYear() is almost like the ISO 8601 week when passed CalendarWeekRule.FirstFourDayWeek and DayOfWeek.Monday, however it is a little bit different. Specifically ISO 8601 always has 7 day weeks. " blogs.msdn.microsoft.com/shawnste/2006/01/24/…

            – Juha Palomäki
            Jan 31 '17 at 22:45
















          13














          This is the way:



          public int GetWeekNumber()
          {
          CultureInfo ciCurr = CultureInfo.CurrentCulture;
          int weekNum = ciCurr.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
          return weekNum;
          }


          Most important for is the CalendarWeekRule parameter.



          See here:
          https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=IT-IT&k=k(System.Globalization.CalendarWeekRule);k(TargetFrameworkMoniker-.NETFramework






          share|improve this answer
























          • "Several people have noticed that Calendar.GetWeekOfYear() is almost like the ISO 8601 week when passed CalendarWeekRule.FirstFourDayWeek and DayOfWeek.Monday, however it is a little bit different. Specifically ISO 8601 always has 7 day weeks. " blogs.msdn.microsoft.com/shawnste/2006/01/24/…

            – Juha Palomäki
            Jan 31 '17 at 22:45














          13












          13








          13







          This is the way:



          public int GetWeekNumber()
          {
          CultureInfo ciCurr = CultureInfo.CurrentCulture;
          int weekNum = ciCurr.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
          return weekNum;
          }


          Most important for is the CalendarWeekRule parameter.



          See here:
          https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=IT-IT&k=k(System.Globalization.CalendarWeekRule);k(TargetFrameworkMoniker-.NETFramework






          share|improve this answer













          This is the way:



          public int GetWeekNumber()
          {
          CultureInfo ciCurr = CultureInfo.CurrentCulture;
          int weekNum = ciCurr.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
          return weekNum;
          }


          Most important for is the CalendarWeekRule parameter.



          See here:
          https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=IT-IT&k=k(System.Globalization.CalendarWeekRule);k(TargetFrameworkMoniker-.NETFramework







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Aug 19 '16 at 8:59









          daniele3004daniele3004

          5,79373950




          5,79373950













          • "Several people have noticed that Calendar.GetWeekOfYear() is almost like the ISO 8601 week when passed CalendarWeekRule.FirstFourDayWeek and DayOfWeek.Monday, however it is a little bit different. Specifically ISO 8601 always has 7 day weeks. " blogs.msdn.microsoft.com/shawnste/2006/01/24/…

            – Juha Palomäki
            Jan 31 '17 at 22:45



















          • "Several people have noticed that Calendar.GetWeekOfYear() is almost like the ISO 8601 week when passed CalendarWeekRule.FirstFourDayWeek and DayOfWeek.Monday, however it is a little bit different. Specifically ISO 8601 always has 7 day weeks. " blogs.msdn.microsoft.com/shawnste/2006/01/24/…

            – Juha Palomäki
            Jan 31 '17 at 22:45

















          "Several people have noticed that Calendar.GetWeekOfYear() is almost like the ISO 8601 week when passed CalendarWeekRule.FirstFourDayWeek and DayOfWeek.Monday, however it is a little bit different. Specifically ISO 8601 always has 7 day weeks. " blogs.msdn.microsoft.com/shawnste/2006/01/24/…

          – Juha Palomäki
          Jan 31 '17 at 22:45





          "Several people have noticed that Calendar.GetWeekOfYear() is almost like the ISO 8601 week when passed CalendarWeekRule.FirstFourDayWeek and DayOfWeek.Monday, however it is a little bit different. Specifically ISO 8601 always has 7 day weeks. " blogs.msdn.microsoft.com/shawnste/2006/01/24/…

          – Juha Palomäki
          Jan 31 '17 at 22:45











          9














          I'm going to play Necromancer here :-)



          Since there doesn't seem to be a .Net-culture that yields the correct ISO-8601 week number, I'd rather bypass the built-in week determination altogether, and do the calculation manually, instead of attempting to correct a partially correct result.



          What I ended up with is the following extension method:



          /// <summary>
          /// Converts a date to a week number.
          /// ISO 8601 week 1 is the week that contains the first Thursday that year.
          /// </summary>
          public static int ToIso8601Weeknumber(this DateTime date)
          {
          var thursday = date.AddDays(3 - date.DayOfWeek.DayOffset());
          return (thursday.DayOfYear - 1) / 7 + 1;
          }

          /// <summary>
          /// Converts a week number to a date.
          /// Note: Week 1 of a year may start in the previous year.
          /// ISO 8601 week 1 is the week that contains the first Thursday that year, so
          /// if December 28 is a Monday, December 31 is a Thursday,
          /// and week 1 starts January 4.
          /// If December 28 is a later day in the week, week 1 starts earlier.
          /// If December 28 is a Sunday, it is in the same week as Thursday January 1.
          /// </summary>
          public static DateTime FromIso8601Weeknumber(int weekNumber, int? year = null, DayOfWeek day = DayOfWeek.Monday)
          {
          var dec28 = new DateTime((year ?? DateTime.Today.Year) - 1, 12, 28);
          var monday = dec28.AddDays(7 * weekNumber - dec28.DayOfWeek.DayOffset());
          return monday.AddDays(day.DayOffset());
          }

          /// <summary>
          /// Iso8601 weeks start on Monday. This returns 0 for Monday.
          /// </summary>
          private static int DayOffset(this DayOfWeek weekDay)
          {
          return ((int)weekDay + 6) % 7;
          }




          First of all, ((int)date.DayOfWeek + 6) % 7) determines the weekday number, 0=monday, 6=sunday.



          date.AddDays(-((int)date.DayOfWeek + 6) % 7) determines the date of the monday preceiding the requested week number.



          Three days later is the target thursday, which determines what year the week is in.



          If you divide the (zero based) day-number within the year by seven (round down), you get the (zero based) week number in the year.



          In c#, integer calculation results are round down implicitly.






          share|improve this answer






























            9














            I'm going to play Necromancer here :-)



            Since there doesn't seem to be a .Net-culture that yields the correct ISO-8601 week number, I'd rather bypass the built-in week determination altogether, and do the calculation manually, instead of attempting to correct a partially correct result.



            What I ended up with is the following extension method:



            /// <summary>
            /// Converts a date to a week number.
            /// ISO 8601 week 1 is the week that contains the first Thursday that year.
            /// </summary>
            public static int ToIso8601Weeknumber(this DateTime date)
            {
            var thursday = date.AddDays(3 - date.DayOfWeek.DayOffset());
            return (thursday.DayOfYear - 1) / 7 + 1;
            }

            /// <summary>
            /// Converts a week number to a date.
            /// Note: Week 1 of a year may start in the previous year.
            /// ISO 8601 week 1 is the week that contains the first Thursday that year, so
            /// if December 28 is a Monday, December 31 is a Thursday,
            /// and week 1 starts January 4.
            /// If December 28 is a later day in the week, week 1 starts earlier.
            /// If December 28 is a Sunday, it is in the same week as Thursday January 1.
            /// </summary>
            public static DateTime FromIso8601Weeknumber(int weekNumber, int? year = null, DayOfWeek day = DayOfWeek.Monday)
            {
            var dec28 = new DateTime((year ?? DateTime.Today.Year) - 1, 12, 28);
            var monday = dec28.AddDays(7 * weekNumber - dec28.DayOfWeek.DayOffset());
            return monday.AddDays(day.DayOffset());
            }

            /// <summary>
            /// Iso8601 weeks start on Monday. This returns 0 for Monday.
            /// </summary>
            private static int DayOffset(this DayOfWeek weekDay)
            {
            return ((int)weekDay + 6) % 7;
            }




            First of all, ((int)date.DayOfWeek + 6) % 7) determines the weekday number, 0=monday, 6=sunday.



            date.AddDays(-((int)date.DayOfWeek + 6) % 7) determines the date of the monday preceiding the requested week number.



            Three days later is the target thursday, which determines what year the week is in.



            If you divide the (zero based) day-number within the year by seven (round down), you get the (zero based) week number in the year.



            In c#, integer calculation results are round down implicitly.






            share|improve this answer




























              9












              9








              9







              I'm going to play Necromancer here :-)



              Since there doesn't seem to be a .Net-culture that yields the correct ISO-8601 week number, I'd rather bypass the built-in week determination altogether, and do the calculation manually, instead of attempting to correct a partially correct result.



              What I ended up with is the following extension method:



              /// <summary>
              /// Converts a date to a week number.
              /// ISO 8601 week 1 is the week that contains the first Thursday that year.
              /// </summary>
              public static int ToIso8601Weeknumber(this DateTime date)
              {
              var thursday = date.AddDays(3 - date.DayOfWeek.DayOffset());
              return (thursday.DayOfYear - 1) / 7 + 1;
              }

              /// <summary>
              /// Converts a week number to a date.
              /// Note: Week 1 of a year may start in the previous year.
              /// ISO 8601 week 1 is the week that contains the first Thursday that year, so
              /// if December 28 is a Monday, December 31 is a Thursday,
              /// and week 1 starts January 4.
              /// If December 28 is a later day in the week, week 1 starts earlier.
              /// If December 28 is a Sunday, it is in the same week as Thursday January 1.
              /// </summary>
              public static DateTime FromIso8601Weeknumber(int weekNumber, int? year = null, DayOfWeek day = DayOfWeek.Monday)
              {
              var dec28 = new DateTime((year ?? DateTime.Today.Year) - 1, 12, 28);
              var monday = dec28.AddDays(7 * weekNumber - dec28.DayOfWeek.DayOffset());
              return monday.AddDays(day.DayOffset());
              }

              /// <summary>
              /// Iso8601 weeks start on Monday. This returns 0 for Monday.
              /// </summary>
              private static int DayOffset(this DayOfWeek weekDay)
              {
              return ((int)weekDay + 6) % 7;
              }




              First of all, ((int)date.DayOfWeek + 6) % 7) determines the weekday number, 0=monday, 6=sunday.



              date.AddDays(-((int)date.DayOfWeek + 6) % 7) determines the date of the monday preceiding the requested week number.



              Three days later is the target thursday, which determines what year the week is in.



              If you divide the (zero based) day-number within the year by seven (round down), you get the (zero based) week number in the year.



              In c#, integer calculation results are round down implicitly.






              share|improve this answer















              I'm going to play Necromancer here :-)



              Since there doesn't seem to be a .Net-culture that yields the correct ISO-8601 week number, I'd rather bypass the built-in week determination altogether, and do the calculation manually, instead of attempting to correct a partially correct result.



              What I ended up with is the following extension method:



              /// <summary>
              /// Converts a date to a week number.
              /// ISO 8601 week 1 is the week that contains the first Thursday that year.
              /// </summary>
              public static int ToIso8601Weeknumber(this DateTime date)
              {
              var thursday = date.AddDays(3 - date.DayOfWeek.DayOffset());
              return (thursday.DayOfYear - 1) / 7 + 1;
              }

              /// <summary>
              /// Converts a week number to a date.
              /// Note: Week 1 of a year may start in the previous year.
              /// ISO 8601 week 1 is the week that contains the first Thursday that year, so
              /// if December 28 is a Monday, December 31 is a Thursday,
              /// and week 1 starts January 4.
              /// If December 28 is a later day in the week, week 1 starts earlier.
              /// If December 28 is a Sunday, it is in the same week as Thursday January 1.
              /// </summary>
              public static DateTime FromIso8601Weeknumber(int weekNumber, int? year = null, DayOfWeek day = DayOfWeek.Monday)
              {
              var dec28 = new DateTime((year ?? DateTime.Today.Year) - 1, 12, 28);
              var monday = dec28.AddDays(7 * weekNumber - dec28.DayOfWeek.DayOffset());
              return monday.AddDays(day.DayOffset());
              }

              /// <summary>
              /// Iso8601 weeks start on Monday. This returns 0 for Monday.
              /// </summary>
              private static int DayOffset(this DayOfWeek weekDay)
              {
              return ((int)weekDay + 6) % 7;
              }




              First of all, ((int)date.DayOfWeek + 6) % 7) determines the weekday number, 0=monday, 6=sunday.



              date.AddDays(-((int)date.DayOfWeek + 6) % 7) determines the date of the monday preceiding the requested week number.



              Three days later is the target thursday, which determines what year the week is in.



              If you divide the (zero based) day-number within the year by seven (round down), you get the (zero based) week number in the year.



              In c#, integer calculation results are round down implicitly.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Sep 17 '18 at 21:01









              Juan Castillo

              3,55332836




              3,55332836










              answered Sep 18 '15 at 13:19









              realbartrealbart

              2,0591721




              2,0591721























                  4














                  Good news! A pull request adding System.Globalization.ISOWeek to .NET Core was just merged and is currently slated for the 3.0 release. Hopefully it will propagate to the other .NET platforms in a not-too-distant future.



                  The type has the following signature, which should cover most ISO week needs:



                  namespace System.Globalization
                  {
                  public static class ISOWeek
                  {
                  public static int GetWeekOfYear(DateTime date);
                  public static int GetWeeksInYear(int year);
                  public static int GetYear(DateTime date);
                  public static DateTime GetYearEnd(int year);
                  public static DateTime GetYearStart(int year);
                  public static DateTime ToDateTime(int year, int week, DayOfWeek dayOfWeek);
                  }
                  }


                  You can find the source code here.






                  share|improve this answer
























                  • Any idea when v 3.0 will be released?

                    – Jacques
                    Aug 1 '18 at 8:25











                  • "We are planning on releasing a first preview of .NET Core 3 later this year and the final version in 2019." (from the roadmap blog post)

                    – khellang
                    Aug 1 '18 at 8:41








                  • 1





                    But based on the roadmap, there should be a 2.2 release this year as well, which should include these APIs.

                    – khellang
                    Aug 1 '18 at 8:44
















                  4














                  Good news! A pull request adding System.Globalization.ISOWeek to .NET Core was just merged and is currently slated for the 3.0 release. Hopefully it will propagate to the other .NET platforms in a not-too-distant future.



                  The type has the following signature, which should cover most ISO week needs:



                  namespace System.Globalization
                  {
                  public static class ISOWeek
                  {
                  public static int GetWeekOfYear(DateTime date);
                  public static int GetWeeksInYear(int year);
                  public static int GetYear(DateTime date);
                  public static DateTime GetYearEnd(int year);
                  public static DateTime GetYearStart(int year);
                  public static DateTime ToDateTime(int year, int week, DayOfWeek dayOfWeek);
                  }
                  }


                  You can find the source code here.






                  share|improve this answer
























                  • Any idea when v 3.0 will be released?

                    – Jacques
                    Aug 1 '18 at 8:25











                  • "We are planning on releasing a first preview of .NET Core 3 later this year and the final version in 2019." (from the roadmap blog post)

                    – khellang
                    Aug 1 '18 at 8:41








                  • 1





                    But based on the roadmap, there should be a 2.2 release this year as well, which should include these APIs.

                    – khellang
                    Aug 1 '18 at 8:44














                  4












                  4








                  4







                  Good news! A pull request adding System.Globalization.ISOWeek to .NET Core was just merged and is currently slated for the 3.0 release. Hopefully it will propagate to the other .NET platforms in a not-too-distant future.



                  The type has the following signature, which should cover most ISO week needs:



                  namespace System.Globalization
                  {
                  public static class ISOWeek
                  {
                  public static int GetWeekOfYear(DateTime date);
                  public static int GetWeeksInYear(int year);
                  public static int GetYear(DateTime date);
                  public static DateTime GetYearEnd(int year);
                  public static DateTime GetYearStart(int year);
                  public static DateTime ToDateTime(int year, int week, DayOfWeek dayOfWeek);
                  }
                  }


                  You can find the source code here.






                  share|improve this answer













                  Good news! A pull request adding System.Globalization.ISOWeek to .NET Core was just merged and is currently slated for the 3.0 release. Hopefully it will propagate to the other .NET platforms in a not-too-distant future.



                  The type has the following signature, which should cover most ISO week needs:



                  namespace System.Globalization
                  {
                  public static class ISOWeek
                  {
                  public static int GetWeekOfYear(DateTime date);
                  public static int GetWeeksInYear(int year);
                  public static int GetYear(DateTime date);
                  public static DateTime GetYearEnd(int year);
                  public static DateTime GetYearStart(int year);
                  public static DateTime ToDateTime(int year, int week, DayOfWeek dayOfWeek);
                  }
                  }


                  You can find the source code here.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jun 19 '18 at 10:24









                  khellangkhellang

                  13.1k54471




                  13.1k54471













                  • Any idea when v 3.0 will be released?

                    – Jacques
                    Aug 1 '18 at 8:25











                  • "We are planning on releasing a first preview of .NET Core 3 later this year and the final version in 2019." (from the roadmap blog post)

                    – khellang
                    Aug 1 '18 at 8:41








                  • 1





                    But based on the roadmap, there should be a 2.2 release this year as well, which should include these APIs.

                    – khellang
                    Aug 1 '18 at 8:44



















                  • Any idea when v 3.0 will be released?

                    – Jacques
                    Aug 1 '18 at 8:25











                  • "We are planning on releasing a first preview of .NET Core 3 later this year and the final version in 2019." (from the roadmap blog post)

                    – khellang
                    Aug 1 '18 at 8:41








                  • 1





                    But based on the roadmap, there should be a 2.2 release this year as well, which should include these APIs.

                    – khellang
                    Aug 1 '18 at 8:44

















                  Any idea when v 3.0 will be released?

                  – Jacques
                  Aug 1 '18 at 8:25





                  Any idea when v 3.0 will be released?

                  – Jacques
                  Aug 1 '18 at 8:25













                  "We are planning on releasing a first preview of .NET Core 3 later this year and the final version in 2019." (from the roadmap blog post)

                  – khellang
                  Aug 1 '18 at 8:41







                  "We are planning on releasing a first preview of .NET Core 3 later this year and the final version in 2019." (from the roadmap blog post)

                  – khellang
                  Aug 1 '18 at 8:41






                  1




                  1





                  But based on the roadmap, there should be a 2.2 release this year as well, which should include these APIs.

                  – khellang
                  Aug 1 '18 at 8:44





                  But based on the roadmap, there should be a 2.2 release this year as well, which should include these APIs.

                  – khellang
                  Aug 1 '18 at 8:44











                  3














                  C# to Powershell port from code above from il_guru:



                  function GetWeekOfYear([datetime] $inputDate)
                  {
                  $day = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetDayOfWeek($inputDate)
                  if (($day -ge [System.DayOfWeek]::Monday) -and ($day -le [System.DayOfWeek]::Wednesday))
                  {
                  $inputDate = $inputDate.AddDays(3)
                  }

                  # Return the week of our adjusted day
                  $weekofYear = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetWeekOfYear($inputDate, [System.Globalization.CalendarWeekRule]::FirstFourDayWeek, [System.DayOfWeek]::Monday)
                  return $weekofYear
                  }





                  share|improve this answer





















                  • 1





                    Could you explain your code? Code-only answers are generally not acceptable on StackOverflow, and as such are liable to be deleted.

                    – Wai Ha Lee
                    Oct 1 '15 at 0:20











                  • @Wai Ha Lee the code is already explained. See post above from il_guru. I ported his code to powershell, so other people can use it in powershell because there are no good solution in powershell so far.

                    – Rainer
                    Oct 7 '15 at 11:29











                  • If that's what you did, you should credit the original author in the answer itself. The answer you ported has better comments which you have presumably removed. Also, this isn't an answer to the question since the question did not mention PowerShell.

                    – Wai Ha Lee
                    Oct 7 '15 at 11:32






                  • 1





                    I did now @Wai Ha Lee. The question is already marked as answered, so this would be the same solution written in an other language. I made a favour for people, which are looking for an solution in Powershell language (I was looking hard for an solution in Powershell, but what I found was a solution in C#). The idea remains the same and the author gets the credit for it.

                    – Rainer
                    Oct 7 '15 at 11:39
















                  3














                  C# to Powershell port from code above from il_guru:



                  function GetWeekOfYear([datetime] $inputDate)
                  {
                  $day = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetDayOfWeek($inputDate)
                  if (($day -ge [System.DayOfWeek]::Monday) -and ($day -le [System.DayOfWeek]::Wednesday))
                  {
                  $inputDate = $inputDate.AddDays(3)
                  }

                  # Return the week of our adjusted day
                  $weekofYear = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetWeekOfYear($inputDate, [System.Globalization.CalendarWeekRule]::FirstFourDayWeek, [System.DayOfWeek]::Monday)
                  return $weekofYear
                  }





                  share|improve this answer





















                  • 1





                    Could you explain your code? Code-only answers are generally not acceptable on StackOverflow, and as such are liable to be deleted.

                    – Wai Ha Lee
                    Oct 1 '15 at 0:20











                  • @Wai Ha Lee the code is already explained. See post above from il_guru. I ported his code to powershell, so other people can use it in powershell because there are no good solution in powershell so far.

                    – Rainer
                    Oct 7 '15 at 11:29











                  • If that's what you did, you should credit the original author in the answer itself. The answer you ported has better comments which you have presumably removed. Also, this isn't an answer to the question since the question did not mention PowerShell.

                    – Wai Ha Lee
                    Oct 7 '15 at 11:32






                  • 1





                    I did now @Wai Ha Lee. The question is already marked as answered, so this would be the same solution written in an other language. I made a favour for people, which are looking for an solution in Powershell language (I was looking hard for an solution in Powershell, but what I found was a solution in C#). The idea remains the same and the author gets the credit for it.

                    – Rainer
                    Oct 7 '15 at 11:39














                  3












                  3








                  3







                  C# to Powershell port from code above from il_guru:



                  function GetWeekOfYear([datetime] $inputDate)
                  {
                  $day = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetDayOfWeek($inputDate)
                  if (($day -ge [System.DayOfWeek]::Monday) -and ($day -le [System.DayOfWeek]::Wednesday))
                  {
                  $inputDate = $inputDate.AddDays(3)
                  }

                  # Return the week of our adjusted day
                  $weekofYear = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetWeekOfYear($inputDate, [System.Globalization.CalendarWeekRule]::FirstFourDayWeek, [System.DayOfWeek]::Monday)
                  return $weekofYear
                  }





                  share|improve this answer















                  C# to Powershell port from code above from il_guru:



                  function GetWeekOfYear([datetime] $inputDate)
                  {
                  $day = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetDayOfWeek($inputDate)
                  if (($day -ge [System.DayOfWeek]::Monday) -and ($day -le [System.DayOfWeek]::Wednesday))
                  {
                  $inputDate = $inputDate.AddDays(3)
                  }

                  # Return the week of our adjusted day
                  $weekofYear = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetWeekOfYear($inputDate, [System.Globalization.CalendarWeekRule]::FirstFourDayWeek, [System.DayOfWeek]::Monday)
                  return $weekofYear
                  }






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 7 '15 at 11:33

























                  answered Sep 30 '15 at 16:31









                  RainerRainer

                  34934




                  34934








                  • 1





                    Could you explain your code? Code-only answers are generally not acceptable on StackOverflow, and as such are liable to be deleted.

                    – Wai Ha Lee
                    Oct 1 '15 at 0:20











                  • @Wai Ha Lee the code is already explained. See post above from il_guru. I ported his code to powershell, so other people can use it in powershell because there are no good solution in powershell so far.

                    – Rainer
                    Oct 7 '15 at 11:29











                  • If that's what you did, you should credit the original author in the answer itself. The answer you ported has better comments which you have presumably removed. Also, this isn't an answer to the question since the question did not mention PowerShell.

                    – Wai Ha Lee
                    Oct 7 '15 at 11:32






                  • 1





                    I did now @Wai Ha Lee. The question is already marked as answered, so this would be the same solution written in an other language. I made a favour for people, which are looking for an solution in Powershell language (I was looking hard for an solution in Powershell, but what I found was a solution in C#). The idea remains the same and the author gets the credit for it.

                    – Rainer
                    Oct 7 '15 at 11:39














                  • 1





                    Could you explain your code? Code-only answers are generally not acceptable on StackOverflow, and as such are liable to be deleted.

                    – Wai Ha Lee
                    Oct 1 '15 at 0:20











                  • @Wai Ha Lee the code is already explained. See post above from il_guru. I ported his code to powershell, so other people can use it in powershell because there are no good solution in powershell so far.

                    – Rainer
                    Oct 7 '15 at 11:29











                  • If that's what you did, you should credit the original author in the answer itself. The answer you ported has better comments which you have presumably removed. Also, this isn't an answer to the question since the question did not mention PowerShell.

                    – Wai Ha Lee
                    Oct 7 '15 at 11:32






                  • 1





                    I did now @Wai Ha Lee. The question is already marked as answered, so this would be the same solution written in an other language. I made a favour for people, which are looking for an solution in Powershell language (I was looking hard for an solution in Powershell, but what I found was a solution in C#). The idea remains the same and the author gets the credit for it.

                    – Rainer
                    Oct 7 '15 at 11:39








                  1




                  1





                  Could you explain your code? Code-only answers are generally not acceptable on StackOverflow, and as such are liable to be deleted.

                  – Wai Ha Lee
                  Oct 1 '15 at 0:20





                  Could you explain your code? Code-only answers are generally not acceptable on StackOverflow, and as such are liable to be deleted.

                  – Wai Ha Lee
                  Oct 1 '15 at 0:20













                  @Wai Ha Lee the code is already explained. See post above from il_guru. I ported his code to powershell, so other people can use it in powershell because there are no good solution in powershell so far.

                  – Rainer
                  Oct 7 '15 at 11:29





                  @Wai Ha Lee the code is already explained. See post above from il_guru. I ported his code to powershell, so other people can use it in powershell because there are no good solution in powershell so far.

                  – Rainer
                  Oct 7 '15 at 11:29













                  If that's what you did, you should credit the original author in the answer itself. The answer you ported has better comments which you have presumably removed. Also, this isn't an answer to the question since the question did not mention PowerShell.

                  – Wai Ha Lee
                  Oct 7 '15 at 11:32





                  If that's what you did, you should credit the original author in the answer itself. The answer you ported has better comments which you have presumably removed. Also, this isn't an answer to the question since the question did not mention PowerShell.

                  – Wai Ha Lee
                  Oct 7 '15 at 11:32




                  1




                  1





                  I did now @Wai Ha Lee. The question is already marked as answered, so this would be the same solution written in an other language. I made a favour for people, which are looking for an solution in Powershell language (I was looking hard for an solution in Powershell, but what I found was a solution in C#). The idea remains the same and the author gets the credit for it.

                  – Rainer
                  Oct 7 '15 at 11:39





                  I did now @Wai Ha Lee. The question is already marked as answered, so this would be the same solution written in an other language. I made a favour for people, which are looking for an solution in Powershell language (I was looking hard for an solution in Powershell, but what I found was a solution in C#). The idea remains the same and the author gets the credit for it.

                  – Rainer
                  Oct 7 '15 at 11:39











                  2














                  The easiest way to determine the week number ISO 8601 style using c# and the DateTime class.



                  Ask this: the how-many-eth thursday of the year is the thursday of this week.
                  The answer equals the wanted week number.



                  var dayOfWeek = (int)moment.DayOfWeek;
                  // Make monday the first day of the week
                  if (--dayOfWeek < 0)
                  dayOfWeek = 6;
                  // The whole nr of weeks before this thursday plus one is the week number
                  var weekNumber = (moment.AddDays(3 - dayOfWeek).DayOfYear - 1) / 7 + 1;





                  share|improve this answer




























                    2














                    The easiest way to determine the week number ISO 8601 style using c# and the DateTime class.



                    Ask this: the how-many-eth thursday of the year is the thursday of this week.
                    The answer equals the wanted week number.



                    var dayOfWeek = (int)moment.DayOfWeek;
                    // Make monday the first day of the week
                    if (--dayOfWeek < 0)
                    dayOfWeek = 6;
                    // The whole nr of weeks before this thursday plus one is the week number
                    var weekNumber = (moment.AddDays(3 - dayOfWeek).DayOfYear - 1) / 7 + 1;





                    share|improve this answer


























                      2












                      2








                      2







                      The easiest way to determine the week number ISO 8601 style using c# and the DateTime class.



                      Ask this: the how-many-eth thursday of the year is the thursday of this week.
                      The answer equals the wanted week number.



                      var dayOfWeek = (int)moment.DayOfWeek;
                      // Make monday the first day of the week
                      if (--dayOfWeek < 0)
                      dayOfWeek = 6;
                      // The whole nr of weeks before this thursday plus one is the week number
                      var weekNumber = (moment.AddDays(3 - dayOfWeek).DayOfYear - 1) / 7 + 1;





                      share|improve this answer













                      The easiest way to determine the week number ISO 8601 style using c# and the DateTime class.



                      Ask this: the how-many-eth thursday of the year is the thursday of this week.
                      The answer equals the wanted week number.



                      var dayOfWeek = (int)moment.DayOfWeek;
                      // Make monday the first day of the week
                      if (--dayOfWeek < 0)
                      dayOfWeek = 6;
                      // The whole nr of weeks before this thursday plus one is the week number
                      var weekNumber = (moment.AddDays(3 - dayOfWeek).DayOfYear - 1) / 7 + 1;






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered May 2 '17 at 11:28









                      user6887101user6887101

                      212




                      212























                          1














                          var cultureInfo = CultureInfo.CurrentCulture;
                          var calendar = cultureInfo.Calendar;

                          var calendarWeekRule = cultureInfo.DateTimeFormat.CalendarWeekRule;
                          var firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
                          var lastDayOfWeek = cultureInfo.LCID == 1033 //En-us
                          ? DayOfWeek.Saturday
                          : DayOfWeek.Sunday;

                          var lastDayOfYear = new DateTime(date.Year, 12, 31);

                          var weekNumber = calendar.GetWeekOfYear(date, calendarWeekRule, firstDayOfWeek);

                          //Check if this is the last week in the year and it doesn`t occupy the whole week
                          return weekNumber == 53 && lastDayOfYear.DayOfWeek != lastDayOfWeek
                          ? 1
                          : weekNumber;


                          It works well both for US and Russian cultures. ISO 8601 also will be correct, `cause Russian week starts at Monday.






                          share|improve this answer






























                            1














                            var cultureInfo = CultureInfo.CurrentCulture;
                            var calendar = cultureInfo.Calendar;

                            var calendarWeekRule = cultureInfo.DateTimeFormat.CalendarWeekRule;
                            var firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
                            var lastDayOfWeek = cultureInfo.LCID == 1033 //En-us
                            ? DayOfWeek.Saturday
                            : DayOfWeek.Sunday;

                            var lastDayOfYear = new DateTime(date.Year, 12, 31);

                            var weekNumber = calendar.GetWeekOfYear(date, calendarWeekRule, firstDayOfWeek);

                            //Check if this is the last week in the year and it doesn`t occupy the whole week
                            return weekNumber == 53 && lastDayOfYear.DayOfWeek != lastDayOfWeek
                            ? 1
                            : weekNumber;


                            It works well both for US and Russian cultures. ISO 8601 also will be correct, `cause Russian week starts at Monday.






                            share|improve this answer




























                              1












                              1








                              1







                              var cultureInfo = CultureInfo.CurrentCulture;
                              var calendar = cultureInfo.Calendar;

                              var calendarWeekRule = cultureInfo.DateTimeFormat.CalendarWeekRule;
                              var firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
                              var lastDayOfWeek = cultureInfo.LCID == 1033 //En-us
                              ? DayOfWeek.Saturday
                              : DayOfWeek.Sunday;

                              var lastDayOfYear = new DateTime(date.Year, 12, 31);

                              var weekNumber = calendar.GetWeekOfYear(date, calendarWeekRule, firstDayOfWeek);

                              //Check if this is the last week in the year and it doesn`t occupy the whole week
                              return weekNumber == 53 && lastDayOfYear.DayOfWeek != lastDayOfWeek
                              ? 1
                              : weekNumber;


                              It works well both for US and Russian cultures. ISO 8601 also will be correct, `cause Russian week starts at Monday.






                              share|improve this answer















                              var cultureInfo = CultureInfo.CurrentCulture;
                              var calendar = cultureInfo.Calendar;

                              var calendarWeekRule = cultureInfo.DateTimeFormat.CalendarWeekRule;
                              var firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
                              var lastDayOfWeek = cultureInfo.LCID == 1033 //En-us
                              ? DayOfWeek.Saturday
                              : DayOfWeek.Sunday;

                              var lastDayOfYear = new DateTime(date.Year, 12, 31);

                              var weekNumber = calendar.GetWeekOfYear(date, calendarWeekRule, firstDayOfWeek);

                              //Check if this is the last week in the year and it doesn`t occupy the whole week
                              return weekNumber == 53 && lastDayOfYear.DayOfWeek != lastDayOfWeek
                              ? 1
                              : weekNumber;


                              It works well both for US and Russian cultures. ISO 8601 also will be correct, `cause Russian week starts at Monday.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jun 11 '14 at 10:10

























                              answered Jun 11 '14 at 9:00









                              Donskikh AndreiDonskikh Andrei

                              9041312




                              9041312























                                  0














                                  The question is: How do you define if a week is in 2012 or in 2013?
                                  Your supposition, I guess, is that since 6 days of the week are in 2013, this week should be marked as the first week of 2013.



                                  Not sure if this is the right way to go.
                                  That week started on 2012 (On monday 31th Dec), so it should be marked as the last week of 2012, therefore it should be the 53rd of 2012. The first week of 2013 should start on monday the 7th.



                                  Now, you can handle the particular case of edge weeks (first and last week of the year) using the day of week information. It all depends on your logic.






                                  share|improve this answer


























                                  • Okay, I can see your point. The thing is when I use 2013/01/07 in any of my methods, it say week 2. So, 2012/12/31 is week 53 and 2013/01/07 is week 2. You might think there is no week 1 of 2013. But when I try 2013/01/01 it says week 1.

                                    – Amberlamps
                                    Jun 22 '12 at 11:11


















                                  0














                                  The question is: How do you define if a week is in 2012 or in 2013?
                                  Your supposition, I guess, is that since 6 days of the week are in 2013, this week should be marked as the first week of 2013.



                                  Not sure if this is the right way to go.
                                  That week started on 2012 (On monday 31th Dec), so it should be marked as the last week of 2012, therefore it should be the 53rd of 2012. The first week of 2013 should start on monday the 7th.



                                  Now, you can handle the particular case of edge weeks (first and last week of the year) using the day of week information. It all depends on your logic.






                                  share|improve this answer


























                                  • Okay, I can see your point. The thing is when I use 2013/01/07 in any of my methods, it say week 2. So, 2012/12/31 is week 53 and 2013/01/07 is week 2. You might think there is no week 1 of 2013. But when I try 2013/01/01 it says week 1.

                                    – Amberlamps
                                    Jun 22 '12 at 11:11
















                                  0












                                  0








                                  0







                                  The question is: How do you define if a week is in 2012 or in 2013?
                                  Your supposition, I guess, is that since 6 days of the week are in 2013, this week should be marked as the first week of 2013.



                                  Not sure if this is the right way to go.
                                  That week started on 2012 (On monday 31th Dec), so it should be marked as the last week of 2012, therefore it should be the 53rd of 2012. The first week of 2013 should start on monday the 7th.



                                  Now, you can handle the particular case of edge weeks (first and last week of the year) using the day of week information. It all depends on your logic.






                                  share|improve this answer















                                  The question is: How do you define if a week is in 2012 or in 2013?
                                  Your supposition, I guess, is that since 6 days of the week are in 2013, this week should be marked as the first week of 2013.



                                  Not sure if this is the right way to go.
                                  That week started on 2012 (On monday 31th Dec), so it should be marked as the last week of 2012, therefore it should be the 53rd of 2012. The first week of 2013 should start on monday the 7th.



                                  Now, you can handle the particular case of edge weeks (first and last week of the year) using the day of week information. It all depends on your logic.







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Jun 22 '12 at 11:00









                                  James

                                  60.7k16120195




                                  60.7k16120195










                                  answered Jun 22 '12 at 10:58









                                  Samy ArousSamy Arous

                                  5,970816




                                  5,970816













                                  • Okay, I can see your point. The thing is when I use 2013/01/07 in any of my methods, it say week 2. So, 2012/12/31 is week 53 and 2013/01/07 is week 2. You might think there is no week 1 of 2013. But when I try 2013/01/01 it says week 1.

                                    – Amberlamps
                                    Jun 22 '12 at 11:11





















                                  • Okay, I can see your point. The thing is when I use 2013/01/07 in any of my methods, it say week 2. So, 2012/12/31 is week 53 and 2013/01/07 is week 2. You might think there is no week 1 of 2013. But when I try 2013/01/01 it says week 1.

                                    – Amberlamps
                                    Jun 22 '12 at 11:11



















                                  Okay, I can see your point. The thing is when I use 2013/01/07 in any of my methods, it say week 2. So, 2012/12/31 is week 53 and 2013/01/07 is week 2. You might think there is no week 1 of 2013. But when I try 2013/01/01 it says week 1.

                                  – Amberlamps
                                  Jun 22 '12 at 11:11







                                  Okay, I can see your point. The thing is when I use 2013/01/07 in any of my methods, it say week 2. So, 2012/12/31 is week 53 and 2013/01/07 is week 2. You might think there is no week 1 of 2013. But when I try 2013/01/01 it says week 1.

                                  – Amberlamps
                                  Jun 22 '12 at 11:11













                                  0














                                    DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
                                  DateTime date1 = new DateTime(2011, 1, 1);
                                  Calendar cal = dfi.Calendar;

                                  Console.WriteLine("{0:d}: Week {1} ({2})", date1,
                                  cal.GetWeekOfYear(date1, dfi.CalendarWeekRule,
                                  dfi.FirstDayOfWeek),
                                  cal.ToString().Substring(cal.ToString().LastIndexOf(".") + 1));





                                  share|improve this answer




























                                    0














                                      DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
                                    DateTime date1 = new DateTime(2011, 1, 1);
                                    Calendar cal = dfi.Calendar;

                                    Console.WriteLine("{0:d}: Week {1} ({2})", date1,
                                    cal.GetWeekOfYear(date1, dfi.CalendarWeekRule,
                                    dfi.FirstDayOfWeek),
                                    cal.ToString().Substring(cal.ToString().LastIndexOf(".") + 1));





                                    share|improve this answer


























                                      0












                                      0








                                      0







                                        DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
                                      DateTime date1 = new DateTime(2011, 1, 1);
                                      Calendar cal = dfi.Calendar;

                                      Console.WriteLine("{0:d}: Week {1} ({2})", date1,
                                      cal.GetWeekOfYear(date1, dfi.CalendarWeekRule,
                                      dfi.FirstDayOfWeek),
                                      cal.ToString().Substring(cal.ToString().LastIndexOf(".") + 1));





                                      share|improve this answer













                                        DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
                                      DateTime date1 = new DateTime(2011, 1, 1);
                                      Calendar cal = dfi.Calendar;

                                      Console.WriteLine("{0:d}: Week {1} ({2})", date1,
                                      cal.GetWeekOfYear(date1, dfi.CalendarWeekRule,
                                      dfi.FirstDayOfWeek),
                                      cal.ToString().Substring(cal.ToString().LastIndexOf(".") + 1));






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Mar 1 '17 at 6:40









                                      ImranImran

                                      96657




                                      96657























                                          -1














                                          A year has 52 weeks and 1 day or 2 in case of a lap year (52 x 7 = 364). 2012-12-31 would be week 53, a week that would only have 2 days because 2012 is a lap year.






                                          share|improve this answer
























                                          • This is incorrect. The first day of the week of the year may fall on any day of the week, depending on how you count the weeks, the year may have a 54th week.

                                            – krowe2
                                            Jul 17 '18 at 20:22


















                                          -1














                                          A year has 52 weeks and 1 day or 2 in case of a lap year (52 x 7 = 364). 2012-12-31 would be week 53, a week that would only have 2 days because 2012 is a lap year.






                                          share|improve this answer
























                                          • This is incorrect. The first day of the week of the year may fall on any day of the week, depending on how you count the weeks, the year may have a 54th week.

                                            – krowe2
                                            Jul 17 '18 at 20:22
















                                          -1












                                          -1








                                          -1







                                          A year has 52 weeks and 1 day or 2 in case of a lap year (52 x 7 = 364). 2012-12-31 would be week 53, a week that would only have 2 days because 2012 is a lap year.






                                          share|improve this answer













                                          A year has 52 weeks and 1 day or 2 in case of a lap year (52 x 7 = 364). 2012-12-31 would be week 53, a week that would only have 2 days because 2012 is a lap year.







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Jun 22 '12 at 10:54









                                          CarlosJCarlosJ

                                          204313




                                          204313













                                          • This is incorrect. The first day of the week of the year may fall on any day of the week, depending on how you count the weeks, the year may have a 54th week.

                                            – krowe2
                                            Jul 17 '18 at 20:22





















                                          • This is incorrect. The first day of the week of the year may fall on any day of the week, depending on how you count the weeks, the year may have a 54th week.

                                            – krowe2
                                            Jul 17 '18 at 20:22



















                                          This is incorrect. The first day of the week of the year may fall on any day of the week, depending on how you count the weeks, the year may have a 54th week.

                                          – krowe2
                                          Jul 17 '18 at 20:22







                                          This is incorrect. The first day of the week of the year may fall on any day of the week, depending on how you count the weeks, the year may have a 54th week.

                                          – krowe2
                                          Jul 17 '18 at 20:22




















                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11154673%2fget-the-correct-week-number-of-a-given-date%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Lallio

                                          Futebolista

                                          Jornalista