Skip to content Skip to sidebar Skip to footer

Get The Current Week Using Javascript Without Additional Libraries ? [so Examples Are Broken]

I built a calendar control and was adding the week numbers as a final touch, and encountered a problem with every script example I could find on SO and outside of SO (most of whic

Solution 1:

The algorithm is to use the week number of the following Saturday. So get the following Saturday, then use it's year for the 1st of Jan. If it's not a Sunday, go to the previous Sunday. Then get the number of weeks from there. It might sound a bit convoluted, but it's only a few lines of code. Most of the following is helpers for playing.

Hopefully the comments are sufficient, getWeekNumber returns an array of [year, weekNumber]. Tested against the Mac OS X Calendar, which seems to use the same week numbering. Please test thoroughly, particularly around daylight saving change over.

/* Get week number in year based on:
 *  - week starts on Sunday
 *  - week number and year is that of the next Saturday,
 *    or current date if it's Saturday
 *    1st week of 2011 starts on Sunday 26 December, 2010
 *    1st week of 2017 starts on Sunday 1 January, 2017
 *
 * Calculations use UTC to avoid daylight saving issues.
 *
 * @param {Date} date - date to get week number of
 * @returns {number[]} year and week number
 */functiongetWeekNumber(date) {
  // Copy date as UTC to avoid DSTvar d =  newDate(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
  // Shift to the following Saturday to get the year
  d.setUTCDate(d.getUTCDate() + 6 - d.getUTCDay());
  // Get the first day of the yearvar yearStart = newDate(Date.UTC(d.getUTCFullYear(), 0, 1));
  yearStart.setUTCDate(yearStart.getUTCDate() - yearStart.getUTCDay());
  // Get difference between yearStart and d in milliseconds// Reduce to whole weeksreturn [d.getUTCFullYear(), (Math.ceil((d - yearStart) / 6.048e8))];
}

// Helper to format datesfunctionfDate(d) {
  var opts = {weekday:'short',month:'short',day:'numeric',year:'numeric'};
  return d.toLocaleString(undefined, opts);
}
// Parse yyyy-mm-dd as localfunctionpDate(s){
  var b = (s+'').split(/\D/);
  var d = newDate(b[0],b[1]-1,b[2]);
  return d.getMonth() == b[1]-1? d : newDate(NaN);
}
// Handle button clickfunctiondoButtonClick(){
  var d = pDate(document.getElementById('inp0').value);
  var span = document.getElementById('weekNumber');
  if (isNaN(d)) {
    span.textContent = 'Invalid date';
  } else {
    let [y,w] = getWeekNumber(d);
    span.textContent = `${fDate(d)} is in week ${w} of ${y}`;
  }
}
Date:<inputid="inp0"placeholder="yyyy-mm-dd"><buttontype="button"onclick="doButtonClick()">Get week number</button><br><spanid="weekNumber"></span>

Post a Comment for "Get The Current Week Using Javascript Without Additional Libraries ? [so Examples Are Broken]"