Calculate Date from Week Number in JavaScript

Calculate date from week number in JavaScript

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.

Calculate date from week number, with the week starting on Monday

The code works but has some issues.

return firstMonday.setDate(firstMonday.getDate() + 7 * (weekNo - 1));

returns a time value (the return from setDate). To return a Date, it should be two separate statements:

firstMonday.setDate(firstMonday.getDate() + 7 * (weekNo - 1));
return firstMonday;

Also, looping to find the first Monday is inefficient. It can be calculated from the initial value of firstMonday. Checking for week 53 can also be simplified and the input week number should be tested to ensure it's from 1 to 53.

Lastly, the first couple of days of January may be in the last week of the previous year, so in week 53 getting week 53 with the default year may return the start of week 53 of the wrong year (or undefined, see below). It would be better if the function took two arguments: weekNo and year, where year defaults to the current year and weekNo to the current week.

/* Return date for Monday of supplied ISO week number
* @param {number|string} weekNo - integer from 1 to 53
* @returns {Date} Monday of chosen week or
* undefined if input is invalid
*/
function getFirstMondayOfWeek(weekNo) {
let year = new Date().getFullYear();

// Test weekNo is an integer in range 1 to 53
if (Number.isInteger(+weekNo) && weekNo > 0 && weekNo < 54) {

// Get to Monday of first ISO week of year
var firstMonday = new Date(year, 0, 4);
firstMonday.setDate(firstMonday.getDate() + (1 - firstMonday.getDay()));

// Add required weeks
firstMonday.setDate(firstMonday.getDate() + 7 * (weekNo - 1));

// Check still in correct year (e.g. weekNo 53 in year of 52 weeks)
if (firstMonday.getFullYear() <= year) {
return firstMonday;
}
}
// If not an integer or out of range, return undefined
return;
}

// Test weeks, there is no week 53 in 2021
[0, '1', 34, 52, 53, 54, 'foo'].forEach(weekNo => {
let date = getFirstMondayOfWeek(weekNo);
console.log(`Week ${weekNo}: ${date? date.toDateString() : date}`);
});

how to get a javascript date from a week number?

var d = new Date(year, 0, 1);
var days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];

d.setDate(d.getDate() + (week * 7));

console.log(days[d.getDay()]);

Try This

Javascript - How do i get every date in a week from a given week number and year

Here's an example building on top of: javascript calculate date from week number

Get the first date of the week, then return an array of 7 elements, incrementing the date for each element.

If the day number goes above the number of days in the month, then add one to the month temp.m and reset the day temp.d equal to one.

function getISOWeek(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());
const temp = {
d: ISOweekStart.getDate(),
m: ISOweekStart.getMonth(),
y: ISOweekStart.getFullYear(),
}
//console.log(ISOweekStart)
const numDaysInMonth = new Date(temp.y, temp.m + 1, 0).getDate()

return Array.from({length: 7}, _ => {
if (temp.d > numDaysInMonth){
temp.m +=1;
temp.d = 1;
// not needed, Date(2020, 12, 1) == Date(2021, 0, 1)
/*if (temp.m >= 12){
temp.m = 0
temp.y +=1
}*/
}
return new Date(temp.y, temp.m, temp.d++).toUTCString()
});
}

// var weekNumber = "week + " " + year"; //"35 2020"
const weekNumber = "53 2020";

const weekYearArr = weekNumber.split(" ").map(n => parseInt(n))

const weekOut = getISOWeek(...weekYearArr)

console.log(weekOut);

How to get the date ranges of a given week number in JS

We want to create a date object for the beginning of a given week and the end.

momentjs is a good library to make using date objects much easier.

var moment = require('moment');

function getMonths(weekNumber) {
var beginningOfWeek = moment().week(weekNumber).startOf('week');
var endOfWeek = moment().week(weekNumber).startOf('week').add(6, 'days');
console.log(beginningOfWeek.format('MMMM'));
console.log(endOfWeek.format('MMMM'));
}

Given a week number, we are creating a moment object and another one six days later. Then we log the month at the beginning and end of the week.

Here's an example:

getMonths(5);

January

February

Show week number with Javascript?

Simply add it to your current code, then call (new Date()).getWeek()

<script>
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}

var weekNumber = (new Date()).getWeek();

var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var now = new Date();
document.write(dayNames[now.getDay()] + " (" + weekNumber + ").");
</script>

Get friday from week number and year in javascript

The week #1 is the week with the first Thursday.

Here is a function to get any day:

var w2date = function(year, wn, dayNb){
var j10 = new Date( year,0,10,12,0,0),
j4 = new Date( year,0,4,12,0,0),
mon1 = j4.getTime() - j10.getDay() * 86400000;
return new Date(mon1 + ((wn - 1) * 7 + dayNb) * 86400000);
};
console.log(w2date(2010, 1, 4));

week numbers start at 1 until 52 or 53 it depends the year.

For the day numbers, 0 is Monday, 1 is Tuesday, ... and 4 is Friday

How to get first and last day of the current week in JavaScript

var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6

var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();

firstday
"Sun, 06 Mar 2011 12:25:40 GMT"
lastday
"Sat, 12 Mar 2011 12:25:40 GMT"

This works for firstday = sunday of this week and last day = saturday for this week. Extending it to run Monday to sunday is trivial.

Making it work with first and last days in different months is left as an exercise for the user

Get Date of days of a week given year, month and week number (relative to month) in Javascript / Typescript

If you want Monday as the first day of the week, and the first week of a month is the one with the first Thursday, then you can use a similar algorithm to the year week number function.

So get the start of the required week, then just loop 7 times to get each day. E.g.

/* Return first day of specified week of month of year
**
** @param {number|string} year - year for required week
** @param {number|string} month - month for required week
** Month is calendar month number, 1 = Jan, 2 = Feb, etc.
** @param {number|string} week - week of month
** First week of month is the one with the first Thursday
** @returns {Date} date for Monday at start of required week
*/
function getMonthWeek(year, month, week) {
// Set date to 4th of month
let d = new Date(year, month - 1, 4);
// Get day number, set Sunday to 7
let day = d.getDay() || 7;
// Set to prior Monday
d.setDate(d.getDate() - day + 1);
// Set to required week
d.setDate(d.getDate() + 7 * (week - 1));
return d;
}

// Return array of dates for specified week of month of year
function getWeekDates(year, month, week) {
let d = getMonthWeek(year, month, week);
for (var i=0, arr=[]; i<7; i++) {

// Array of date strings
arr.push(d.toDateString());

// For array of Date objects, replace above with
// arr.push(new Date(d));

// Increment date
d.setDate(d.getDate() + 1);
}
return arr;
}

// Week dates for week 1 of Jan 2020 - week starts in prior year
console.log(getWeekDates(2020, 1, 1));
// Week dates for week 5 of Jan 2020 - 5 week month
console.log(getWeekDates(2020, 1, 5));
// Week dates for week 1 of Oct 2020 - 1st is a Thursday
console.log(getWeekDates(2020, 10, 1));
// Week dates for week 1 of Nov 2020 - 1st is a Sunday
console.log(getWeekDates(2020, 11, 1));


Related Topics



Leave a reply



Submit