Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate date from week number in JavaScript

How can I calculate the date in JavaScript knowing the week number and the year? For week number 20 and year 2013 I want to obtain 2013-05-16. I am trying it like this:

Date.prototype.dayofYear = function () {   var d = new Date(this.getFullYear(), 0, 0)   return Math.floor((/* enter code here */ this - d) / 8.64e + 7) } 
like image 512
user2369009 Avatar asked May 16 '13 14:05

user2369009


People also ask

How do you find the day of the week for any date in Javascript?

getDay() The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.

How do I get this week in Javascript?

var today = new Date(); var startDay = 0; var weekStart = new Date(today. getDate() - (7 + today. getDay() - startDay) % 7); var weekEnd = new Date(today. getDate() + (7 - today.

Which number of week is this?

The current week (week 46) is highlighted.


1 Answers

function getDateOfWeek(w, y) {     var d = (1 + (w - 1) * 7); // 1st of January + 7 days for each week      return new Date(y, 0, d); } 

This uses the simple week definition, meaning the 20th week of 2013 is May 14.

To calculate the date of the start of a given ISO8601 week (which will always be a Monday)

function getDateOfISOWeek(w, y) {     var simple = new Date(y, 0, 1 + (w - 1) * 7);     var dow = simple.getDay();     var ISOweekStart = simple;     if (dow <= 4)         ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);     else         ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());     return ISOweekStart; } 

Result: the 20th week of 2013 is May 13, which can be confirmed here.

like image 156
Elle Avatar answered Sep 20 '22 17:09

Elle