How to get week no from a date like moment("2022-02-28T10:00:53.393Z")
should return 5.
I know about week()
but that return week no from start of year like it will give 11
based on the date.
I need the week no. from month like week 1 of February or week 5 of February
Asked
Active
Viewed 493 times
-5

SaGaR
- 534
- 4
- 11
-
momentjs has special methods for this: [`.week()`](https://momentjs.com/docs/#/get-set/week/) and [`.isoWeek()`](https://momentjs.com/docs/#/get-set/iso-week/) – Andreas Mar 08 '22 at 09:55
-
1[How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Mar 08 '22 at 09:56
-
this one gives the week based on month not year – SaGaR Mar 08 '22 at 09:56
-
1`moment("31/01/2022")` is undefined, unreliable behavior, as you can tell [from the warning you get for it](https://momentjs.com/guides/#/warnings/js-date/). – T.J. Crowder Mar 08 '22 at 09:57
-
@SaGaR - *"this one gives the week based on month not year "* 1. That's not described in the question. 2. What does that even mean? Week in month instead of week in year? If so, it could be a reasonable question if you mean you also want (say) `1` for `2022-02-02`, but you'd have to be clear about it and call out why `week` isn't what you want, a well as defining how weeks are allocated (since it's complicated for week-in-year). – T.J. Crowder Mar 08 '22 at 09:58
-
1[If you add the format and use `weeks()` you'll get `6` as expected](https://jsfiddle.net/c28uyrz0/) – 0stone0 Mar 08 '22 at 10:00
-
1How do you define the first week of a month? As I said above, [it's complicated](https://en.wikipedia.org/wiki/ISO_week_date#First_week) for week-of-year and different locales do it differently. From that link: Jan 1st 1977 is week 53 in the ISO week-of-year system. – T.J. Crowder Mar 08 '22 at 10:06
1 Answers
-5
Here is the solution for this
const getWeekOfDate = (date) => {
let startDate = moment(date).startOf('month').date();
let endDate = moment(date).date();
let weekCount = 1;
for (let i = startDate; i <= endDate; i++) {
if (
moment(date).date(i).format('dddd') ===
moment().startOf('week').format('dddd')
) {
weekCount++;
}
}
return weekCount;
};

SaGaR
- 534
- 4
- 11