-1

Given a specific year, how can I calculate, in javascript/JQuery, how many weeks are in the given year? 52 or 53?

I've looked in many answers but none worked for me yet- I need to calculate the first day of year as the first week (as displayed in Outlook calendar). In the calculations that I saw, the first week starts from the first Sunday in the year.

outlook calendar - 12/2016

YYY
  • 55
  • 1
  • 9
  • Possible duplicate of [leap year calculation](https://stackoverflow.com/questions/725098/leap-year-calculation) – grooveplex Jan 21 '19 at 12:33
  • 4
    `console.log(52)`, beyond that please clarify what you mean by "weeks" here. Do you mean some special handling of partial weeks given a start day of week? – Mark Schultheiss Jan 21 '19 at 12:33
  • "I've looked in many answers" — Which ones? "but none worked for me yet" — Provide a [mcve] of your attempts to implement them, explain how the result is different from what you want. – Quentin Jan 21 '19 at 13:32
  • Sorry, the customer decided to go on the second option (that first week in the year is from the first Sunday) - so my Q is irrelevant now. – YYY Jan 24 '19 at 09:57

1 Answers1

1

If it's the ISO 8601 week number you are looking for you can do this by checking which week number december 28 has as that date is always in the last week of the year like january 4 is always in the first week:

    Date.prototype.getWeek = function() {
      var date = new Date(this.getTime());
      date.setHours(0, 0, 0, 0);
      // Thursday in current week decides the year.
      date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
      // January 4 is always in week 1.
      var week1 = new Date(date.getFullYear(), 0, 4);
      // Adjust to Thursday in week 1 and count number of weeks from date to week1.
      return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
    }

    
    console.log((new Date(2019, 11, 28)).getWeek());  // 52
    console.log((new Date(2020, 11, 28)).getWeek());  // 53
    console.log((new Date(2021, 11, 28)).getWeek());  // 52
Sani Huttunen
  • 23,620
  • 6
  • 72
  • 79
  • Hi, When I run this line: console.log((new Date(2016, 11, 28)).getWeek()); I get 52 weeks. But in outlook weeks I get 53 weeks. The reason for the difference is that the 4/1 is in the second week. Do you know what change should I do in the code in order that it will work? – YYY Jan 23 '19 at 12:54
  • If I change this line like this: var week1 = new Date(date.getFullYear(), 0, 1); it's OK for 2016 but wrong for 2017 :( – YYY Jan 23 '19 at 13:06
  • 2016 has 52 ISO weeks so outlook is wrong. If it's not ISO weeks you are looking for you need to specify exactly what you are looking for. And according to ISO 8601 January 4 is always in week 1. Outlook must be using some other week definition than ISO 8601. Might depend on your locale. – Sani Huttunen Jan 24 '19 at 17:53