Better way to set this in MomentJS

Anyone familiar with MomentJS? What’s a better way to do this? It works, but I want it to work cleaner and without the substr's which I really feel don’t need to be there.

/**
 * Sets the next instance of a weekly event
 * @param  {numbner} day - day of week
 * @param  {string} time - 24hr time
 * @return {object} momentjs object of next occurance
 */
getNextAir(day, time) {
  let _hour = time.substr(0, time.indexOf(':')),
      _min = time.substr(time.indexOf(':')+1, time.length);

  if(day < Moment().utc().day()) {
    day += 7;
  }

  return Moment().utc().weekday(day).hour(_hour).minute(_min).seconds(0);
}

I’ve tried Moment(day +' '+ time, 'e HH:mm'), but that was setting it to the first day of that week in the year. I can’t seem to find an example of what I’m trying to do in the documentation. And this method is the right way, instead of the one above, but I’m missing something.

What about:

let _t = time.split(':');

and

return Moment().utc().weekday(day).hour(_t[0]).min(_t[1]);
2 Likes

Yes, thank you. I didn’t see that… that’s much cleaner too.

I am hoping there is an even cleaner way I can leverage Moment’s parsing. I’m switching to your method until I do though. :smiley:

I can think of other ways, but TBH I wouldn’t consider them “cleaner”
A regex pattern would work, but for the additional overhead, why use it?
The time value could be converted to Unix time, but would need to be converted back.

I guess a lot depends on what you need to do with it. If it’s just to get Day, Hour and Minute returned in “human readable” form I think Stephen’s example is about as clean as you’re going to get.

But I’ve been wrong before.

Well there is a way with ES6 called destructuring, where you can just do:

var [_hour, _min] = time.split(':');

But as we can see from the ES6 compatibility page, support for destructuring is only coming along slowly.

If we come back to the time parsing, have you tried instead setting the day after the time?

return Moment(time, 'HH:mm').utc().weekday(day);

(I’m puzzled about the capital M too, as the moment docs all show lowercase)

1 Like

Neat. I’m using Babel, so it’s fine. I’ve seen that before but forgot about it.

It’s turns into some crazy code with the split though! It adds _slicedToArray() function.

return Moment(time, ‘HH:mm’).utc().weekday(day);

This seems to do what I want it to do! Thank you.

Sorry, that’s just a naming convention I use for requires/imports. I should have changed it before posting.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.