Skip to content
Advertisement

How to get date range from week number with Luxon

I’m searching a way to get date range from week number with Luxon to replace my ‘moment’ code. Today I’m using this code:

m = moment(yearNumber + "-W" + weekNumber);
dateFromStr = moment(m.startOf('week')).add(1, 'day'); // To get Monday 00:00:00
dateToStr = moment(m.endOf('week')).add(1, 'day'); // To get Sunday 23:59:59

I found a way to do that from a month number with ‘DateTime.fromObject()’ but that’s doesn’t work with ‘week’. So I don’t find the best way to do that from a week number 🙁

Thank’s in advance.

Advertisement

Answer

You can use DateTime.fromObject that:

Create a DateTime from a JavaScript object with keys like ‘year’ and ‘hour’ with reasonable defaults.

passing weekYear (an ISO week year) and weekNumber (an ISO week number, between 1 and 52 or 53, depending on the year) in the input object.

Here an live example:

const DateTime = luxon.DateTime;
const yearNumber = 2020;
const weekNumber = 3;
const dt = DateTime.fromObject({
  weekYear: yearNumber,
  weekNumber: weekNumber
});

const dateFromStr = dt.startOf('week');
console.log(dateFromStr.toISO()); // last Monday at 00:00:00
const dateToStr = dt.endOf('week');
console.log(dateToStr.toISO()); // next Sunday at 23:59:59
<script src="https://cdn.jsdelivr.net/npm/luxon@1.26.0/build/global/luxon.js"></script>

You can also use DateTime.fromISO passing ISO compliant format such as YYYY-Www (see more on here). Please note that week number should be two digits.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement