It worked yesterday.
It worked yesterday.

Reputation: 4617

MomentJS get the next specified day within a given duration

I have following variables

let startDay = moment(this.props.startDay); // DD-MM-YYYY HH:mm:ss
let endDay = moment(this.props.endDay); // DD-MM-YYYY HH:mm:ss

I receive a day of week as a string

let day= this.props.day; // 'Ex: Monday'

I am stuck in finding out what the first day that has been set in day within the duration of startDay and endDay; How do I do this in momentJS.

Upvotes: 4

Views: 53

Answers (1)

31piy
31piy

Reputation: 23859

You can loop from start date to end date and in each iteration, can check if the day matches. If the match is found, stop the loop.

let startDay = moment('24-10-2018 12:00:00', 'DD-MM-YYYY HH:mm:ss');
let endDay = moment('01-11-2018 12:00:00', 'DD-MM-YYYY HH');
let day = 'Monday';

while (endDay.diff(startDay, 'day') !== 0) {
  if (startDay.format('dddd') === day) {
    break;
  }
  
  startDay.add(1, 'day');
}

console.log(startDay.format('dddd, DD-MM-YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Upvotes: 1

Related Questions