edward edward - 5 months ago 17
Javascript Question

Is there a way that I can get the (first Sunday in October – first Sunday in April) with moment.js?

I know that I can use this for the start of the month moment().startOf('month') but I need the first Sunday of the month.


You could do this:

function getFirstWeekDay(dateString, dayOfWeek) {
    var date = moment(dateString, "YYYY-MM-DD");

    var day = date.day();
    var diffDays = 0;

    if (day > dayOfWeek) {
      diffDays = 7 - (day - dayOfWeek);
    } else {
      diffDays = dayOfWeek - day

    console.log(date.add(diffDays, 'day').format("YYYY-MM-DD"));

  //Pass in the first of a given calendar month and the day weekday
getFirstWeekDay("2016-10-01", 0);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>