Truncate date string into just year and week

740 Views Asked by At

I'm using Luxon to manipulate Dates in my code. My method returns a date like this:

DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'

I need to knock off the day part and have '1982-W21'instead.

Not too familiar with js, how would I "knock off" the day part..

2

There are 2 best solutions below

0
On BEST ANSWER

You can split, slice and join the result, or extract a substring like this:

console.log('1982-W21-2'.split('-').slice(0, 2).join("-"));

// or
const dateResult = "1982-W21-2'"
console.log(dateResult.substr(0, dateResult.lastIndexOf("-")));

0
On

If you are using Luxon, this method does not provide a formatter, so you need to do minor string manipulation.

This JavaScript will do:

DateTime.utc(1982, 5, 25).toISOWeekDate().split('-').slice(0,2).join('-')

It first splits the string by - into an array (3 members), then creates (slice) a new array from the first two members, and then joins the two members by - again.