0

The problem I have now is that I can't figure out how to get the week of the month a certain date is. I can only find "week of year" in the Moment js docs. For example, if I choose today's date (12/4/2016), I would like to know that this date is in which week of this month of April and also the day(i.e.Tuesday). Any ideas?

user5452972
  • 71
  • 1
  • 9
  • 1
    Are you using the assumption that the first week of a month starts on the 1st and ends on the 7th? – James Donnelly Apr 12 '16 at 09:54
  • What does "week of the month" even mean? – Creynders Apr 12 '16 at 09:55
  • For the day, you have the `day` method. For the week of the month, depends what you mean exactly (that's not clear), but you can use `week` on the given day, and subtract to it the week of the first day of the month – VonD Apr 12 '16 at 09:55
  • 2
    http://stackoverflow.com/questions/21737974/moment-js-how-to-get-week-of-month-google-calendar-style for week of the month and moment(yourDate,"dddd") for the dayname – Xavjer Apr 12 '16 at 09:55
  • As today is 3rd week of the month of April, thats what I mean from week of month – user5452972 Apr 12 '16 at 09:58
  • then `day.week() - day.clone().startOf('month').week() + 1` – VonD Apr 12 '16 at 10:03
  • can u plz write this line of code in detail as I m iOS developer and coding for js first time. – user5452972 Apr 12 '16 at 10:12
  • what more detail do you want ? if `day` is a moment.js object for today, the above line would return 3. `var day = moment(); var weekOfMonth = day.week() - day.clone().startOf('month').week() + 1; // weekOfMonth === 3` – VonD Apr 12 '16 at 10:16
  • Is this syntax according to Parse cloud?? As I m getting error like TypeError: Object function utils_hooks__hooks() { return hookCallback.apply(null, arguments); } has no method 'clone – user5452972 Apr 12 '16 at 10:28
  • well I'm not familiar with parse, but if it is just js this is ok. are you sure you call `clone` on a moment.js object ? – VonD Apr 12 '16 at 10:34
  • Yes, I m writing the same code, which you have suggested – user5452972 Apr 12 '16 at 10:38
  • Then I'd advice opening a new question about parse, so that parse users can answer, this doesn't seem moment.js specific. good luck! – VonD Apr 12 '16 at 10:41

1 Answers1

0

Thanks to @VonD for suggesting. In Parse SDK, week of the month from date can be found as

 var weekOfMonth = moment().isoWeek() - moment().subtract('days', dayCurrent - 1).isoWeek() + 1;

,where dayCurrent is today's day.

And for custom dates(i.e. other than today's date), moment can be customised for that date.

user5452972
  • 71
  • 1
  • 9
  • 1
    Note that week of month is in some ways locale specific. There is a pull request in progress to add this functionality to moment's API: https://github.com/moment/moment/pull/2965 There are more details about the complexities of this in there, but of course if your code meets your needs, then no need to go down that road. – Maggie Pint Apr 12 '16 at 12:45