How to calculate the week of the year in pure Javascript, without relying on libraries?

Asked

Viewed 289 times

0

Below, I present my attempt, which is inconsistent:

function getYearlyWeekNumber(myDate)
{
    var this_date = new Date(myDate.getFullYear(),myDate.getMonth(),myDate.getDate(),0,0,0);
    var y_first_day = new Date(myDate.getFullYear(),0,1,0,0,0);
    var y_first_sun = new Date(myDate.getFullYear(),0,1+y_first_day.getDay(),0,0,0);
    var y_last_sat_before = new Date(myDate.getFullYear(),myDate.getMonth(),myDate.getDate()-myDate.getDay()+1,0,0,0);
    var y_sundaycount = dateDiff('ww', y_first_sun, y_last_sat_before);
    return y_sundaycount + ((y_first_day.getDay()<3) ? 1 : 2);
}

EDIT 20/04/2019: Reworking the calculations (thanks for the considerations). The code below considers Sunday as the first of the week, and uses ISO 8601 to define when the first week begins. It is still incomplete, as stated in the comments.

function getYearlyWeekNumber(myDate)
{
    var today = new Date(myDate.getFullYear(),myDate.getMonth(),myDate.getDate(),0,0,0);
    var first_of_month = new Date(myDate.getFullYear(),myDate.getMonth(),1,0,0,0);
    var first_of_year = new Date(myDate.getFullYear(),0,1,0,0,0);
    var q_dias = dateDiff('d', first_of_year, today);
    var numero_semana = Math.floor(q_dias / 7);
    // ajuste de contagem   
    if (today.getDay()<first_of_year.getDay()) ++numero_semana;
    // ISO 8601
    if (first_of_year.getDay()<=3) ++numero_semana;
    // Datas antes do primeiro Domingo resultarão em zero, 
    // o que significa que pertencem à última semana do ano anterior.
    // Ainda me falta fazer isso. 
    return numero_semana;
}
  • 4

    I also wanted one day to have this functionality without using a library... and ended up writing a library to do this :) Notice that the number of the week is calculated differently in the US and Europe. It is not exactly trivial...

  • 2

    This depends on the definition you will use (which is the first day of the week, and the minimum of days of the first week). The standard ISO 8601, for example, sets the first day = Monday and at least 4 days in the first week - ie, the first week of 2019 is the 7-day period that starts on a Monday and has at least 4 days in 2019 (which is 31/12/18 to 06/01/2019). There are countries where the first day is Sunday and the minimum of days in the first week is 1, so the first week is 30/12/18 to 05/01/19. And there are places where the week starts on Saturday...

  • 1

    In short, it’s not so trivial, and as @Sergio said, you might want to use a lib. The Moment js., for example, it has this functionality.

  • 1

    @hkotsubo Well remembered. I intend to use Sunday as the first of the week (or "head of the week") and adopt the ISO 8601 standard (minimum of 4 days in the first week of the year).

  • 2

    Even so I find it even simpler to use a lib, like Moment.js, which has one function ready for this. I don’t know if it’s worth doing something manually so difficult and error-prone when there is something reliable - there are people who add dependencies for much simpler and unnecessary things, why not add one for complex things? : -) Good, but if you still don’t want to use the lib, vc can be based on their code

  • 1

    @hkotsubo Good! I’ll take a look. I also want to port this functionality to use on a site in ASP Classic (Vbscript) and possibly VBA. Thank you very much !

Show 1 more comment

3 answers

-1


See if this function helps you

function semana(ano,mes,dia) {
function serie(dias) { return 86400000*dias; }
function dateserial(ano,mes,dia) { return (new Date(ano,mes-1,dia).valueOf()); }
function weekdia(date) { return (new Date(date)).getdia()+1; }
function anoserial(date) { return (new Date(date)).getFullano(); }
var date = ano instanceof Date ? ano.valueOf() : typeof ano === "string" ? new Date(ano).valueOf() : dateserial(ano,mes,dia), 
    date2 = dateserial(anoserial(date - serial(weekdia(date-serial(1))) + serial(4)),1,3);
return ~~((date - date2 + serial(weekdia(date2) + 5))/ serial(7));

}

  • I suggested some corrections and put to run in the Chrome console, pasted the result in the Pastebin https://pastebin.com/sr0ekGf9. I believe it is a good way, especially for those who need to start the week on Monday, which can be adapted with some effort. Thank you.

-2

Function

function getYearlyWeekNumber( date ){
  let splitedDate = date.split("-")
  let dateObj = new Date(+splitedDate[0], +splitedDate[1]-1, +splitedDate[2], 0,0,0,0 )
  let firstDayYear = new Date(+splitedDate[0],0,1,0,0,0,0 )
  let yearDay = ((dateObj - firstDayYear) / 86400000)+1
  let weekInYear = +(String((yearDay + firstDayYear.getDay()+1) / 7).split(".")[0])
  return { date, yearDay, weekInYear }
 }
 
console.log( getYearlyWeekNumber("2020-01-01") )
console.log( getYearlyWeekNumber("2020-01-15") ) 
console.log( getYearlyWeekNumber("2020-01-20") ) 

console.log( getYearlyWeekNumber("2020-02-29") ) 
console.log( getYearlyWeekNumber("2020-04-10") ) 
console.log( getYearlyWeekNumber("2020-11-09") )
console.log( getYearlyWeekNumber("2020-12-31") ) 

getYearlyWeekNumber( date ){
                let splitedDate = date.split("-")
                let dateObj = new Date(+splitedDate[0], +splitedDate[1]-1, +splitedDate[2], 0,0,0,0 )
                let firstDayYear = new Date(+splitedDate[0],0,1,0,0,0,0 )
                let yearDay = ((dateObj - firstDayYear) / 86400000)+1
                let weekInYear = +(String((yearDay + firstDayYear.getDay()+1) / 7).split(".")[0])
                return { date, yearDay, weekInYear }
            }

-3

now yes

getYearlyWeekNumber( date ){
  let splitedDate = date.split("-")
  let dateObj = new Date(+splitedDate[0], +splitedDate[1]-1, +splitedDate[2], 0,0,0,0 )
  let firstDayYear = new Date(+splitedDate[0],0,1,0,0,0,0 )
  let yearDay = ((dateObj - firstDayYear) / 86400000)
  let weekInYear = +(String((yearDay + firstDayYear.getDay()) / 7).split(".")[0])
  return { date, yearDay, weekInYear }
}
  • What business is this??? Stack Overflow is not a forum. We’re a question-and-answer site, not just playing a code and the person who turns around. You must teach the concept, the coded solution must be just a complement of proof that the concept taught is correct

Browser other questions tagged

You are not signed in. Login or sign up in order to post.