Moment.js get the week number based on a specific day (also past years)

JavascriptMomentjsWeek Number

Javascript Problem Overview


How could I get from moment JS the week number from a date in the past only from a moment formatted object from a day selected?

Javascript Solutions


Solution 1 - Javascript

  $(document).ready(function(){
    var weeknumber = moment("12-25-1995", "MM-DD-YYYY").week();
    console.log(weeknumber);
  });

According momentjs docs:

> Because different locales define week of year numbering differently, > Moment.js added moment#week to get/set the localized week of the year. > > The week of the year varies depending on which day is the first day of > the week (Sunday, Monday, etc), and which week is the first week of > the year. > > For example, in the United States, Sunday is the first day of the > week. The week with January 1st in it is the first week of the year.

So, if you are having problems getting the right week number use .isoWeek()

$(document).ready(function(){
  var weeknumber = moment("11-26-2016", "MMDDYYYY").isoWeek();
  alert(weeknumber);
});

Example

Solution 2 - Javascript

You can also use format()

Examples:

moment().format('w') // as .week() like '1'
moment().format('W') // as .isoWeek() like '1'
moment().format('ww') // as .week() (2 digits) like '01'
moment().format('WW') // as .isoWeek() (2 digits) like '01'

ISO Week date: https://en.wikipedia.org/wiki/ISO_week_date

More info: https://momentjs.com/docs/#week-year-week-and-weekday-tokens

Solution 3 - Javascript

to get week number by current date

moment(moment().toDate(), "MM-DD-YYYY").isoWeek()

Solution 4 - Javascript

This is not relevant to the question but if you want to get 1 for Monday, 2 for Tuesday, etc moment().format("d")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArthur KovacsView Question on Stackoverflow
Solution 1 - JavascriptGiovaniView Answer on Stackoverflow
Solution 2 - Javascriptl2aelbaView Answer on Stackoverflow
Solution 3 - JavascriptHadeel H Al-HawajrehView Answer on Stackoverflow
Solution 4 - JavascriptPJ3View Answer on Stackoverflow