Calculate Date from Week Number

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

I had issues with the solution by @HenkHolterman even with the fix by @RobinAndersson.

Reading up on the ISO 8601 standard resolves the issue nicely. Use the first Thursday as the target and not Monday. The code below will work for Week 53 of 2009 as well.

public static DateTime FirstDateOfWeekISO8601(int year, int weekOfYear)
{
DateTime jan1 = new DateTime(year, 1, 1);
int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek;

// Use first Thursday in January to get first week of the year as
// it will never be in Week 52/53
DateTime firstThursday = jan1.AddDays(daysOffset);
var cal = CultureInfo.CurrentCulture.Calendar;
int firstWeek = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

var weekNum = weekOfYear;
// As we're adding days to a date in Week 1,
// we need to subtract 1 in order to get the right date for week #1
if (firstWeek == 1)
{
weekNum -= 1;
}

// Using the first Thursday as starting week ensures that we are starting in the right year
// then we add number of weeks multiplied with days
var result = firstThursday.AddDays(weekNum * 7);

// Subtract 3 days from Thursday to get Monday, which is the first weekday in ISO8601
return result.AddDays(-3);
}

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

How to calculate date based on week number in R

You can try this:

first.day <- as.numeric(format(as.Date("2014-01-01"), "%w"))
week <- 10
as.Date("2014-01-01") + week * 7 - first.day
# [1] "2014-03-09"

This assumes weeks start on Sundays. First, find what day of the week Jan 1 is, then, just add 7 * number of weeks to Jan 1, - the day of week Jan 1 is.

Note this is slightly different to what you get if you use %W when doing the reverse, as from that perspective the first day of the week seems to be Monday:

format(seq(as.Date("2014-03-08"), by="1 day", len=5), "%W %A %m-%d")
# [1] "09 Saturday 03-08" "09 Sunday 03-09" "10 Monday 03-10" "10 Tuesday 03-11"
# [5] "10 Wednesday 03-12"

but you can adjust the above code easily if you prefer the Monday centric view.

Get date from weeknumber, dayofweek and year PowerQuery M

This will do it

= Table.AddColumn(Source, "Custom", each Date.From(Number.From(Date.AddDays(Date.FromText("1/1/"&Number.ToText([year])),-3))-Date.DayOfWeek(Date.FromText("1/3/"&Number.ToText([year])))-1+[week]*7+[day]-1) )

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);


Related Topics



Leave a reply



Submit