有没有一种方法可以让我得到(十月的第一个星期日-四月的第一个星期日)的时刻

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

本文关键字:星期日 第一个 十月 时刻 四月 一种 方法 有没有      更新时间:2023-09-26

我知道我可以在月初使用这个moment(). startof ('month'),但是我需要这个月的第一个星期天

你可以这样做:

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>

请检查此代码

var d = new Date();
var first_week = d.getDate();
var the_day = d.getDay();
if(first_week <= 7 && the_day == 0)
{
  // It's the first Sunday of the month
  // Do more stuff here
}

下面是使用js获取任何月份或年份的第一个星期日的示例

function firstSunday(month, year) {
    let tempDate = new Date();
    tempDate.setHours(0,0,0,0);
    // first SUNDAY of april
    tempDate.setMonth(month);
    tempDate.setYear(year);
    tempDate.setDate(1);
    let day = tempDate.getDay();
    let toNextSun = day !== 0 ? 7 - day : 0;
    tempDate.setDate(tempDate.getDate() + toNextSun);
    
    return tempDate.toDateString();
}
console.log("april first sunday" , firstSunday(3 , 2020));
console.log("oct first sunday" , firstSunday(9 , 2020))