Return year and week
millette opened this issue · comments
Looking at the readme, this example cought my attention:
weekNumberSun(new Date(2016, 0, 2, 12)) // Sat
//> 52
weekNumberSun(new Date(2016, 0, 3, 12)) // Sun
//> 1
In the first case, it's actually week 52 of the year 2015. Would you like a patch to return the year along with the week? And while we're here, maybe even return the day (monday=1)
Looking at the ISO 8601 page it lists these examples:
- Monday 29 December 2008 is written "2009-W01-1"
- Sunday 3 January 2010 is written "2009-W53-7"
Maybe another method to return this format? Thoughts?
This snippet returns what is in the README. So no need for a patch.
const {weekNumberSun} = require('weeknumber')
console.log(weekNumberSun(new Date(2016, 0, 2, 12)))
//> 52
With regards to the enhancement proposed. This lib just tries to provide low level functions. Feel free to create a lib which returns the Date in the ISO8601 week format.
I didn't mean the example was wrong, but it's counterintuitive with week 52 coming before week 1 in early 2016. It's how the ISO weeks work, not arguing that.
My use case: group items by year-week in the correct order. I discovered I had a bug since I was using the year (as given to weekNumber and variants) followed by the week - but that assumption is wrong.
In other words, I'm wondering how useful it is to get the week number without its year.
I don't mind writing another package, but I though it would help complete yours. It's fine if you feel otherwise, you can close the issue.
P.S.: I didn't mean to use weekNumberSun when I opened the ticket, but the same applies to any variant.
Finally I got your point. I am used to use-cases where only the calendar-week is required. E.g. like the unix command-line tool ncal -w 2010
.
So for 2008-12-29 its calendar-week 1, albeit calendar-week-year is already 2009.
We could add some functions like that.
const getYear = (date, weekNo) => {
let year = date.getFullYear()
if (date.getMonth() === 11 && week === 1) year++
if (date.getMonth() === 0 && week > 51) year--
return year
}
const weeknumberYear = date => {
const week = weekNumber(date)
const year = getYear(date, week)
const day = date.getDay() || 7
return {year, week, day}
}
const weeknumberYearSun = date => {
const week = weekNumberSun(date)
const year = getYear(date, week)
const day = (date.getDay() + 1) % 7 || 7
return {year, week, day}
}
const weeknumberYearSat = date => {
const week = weekNumberSat(date)
const year = getYear(date, week)
const day = (date.getDay() + 2) % 7 || 7
return {year, week, day}
}
What do you think?
Yeah :-)
Although day should probably start at 1 to be consistent with ISO 8601?
day is in range 1...7.
Doh! Trouble waking up....
Adding this feature would make my day :-)
v1.1.0 should make you happy...