当月的最后一天是周末时,我们如何获取日期到该月的最后一个星期五

时间:2020-04-06 07:57:14

标签: javascript node.js momentjs

当月的最后一天为周末时,我们如何获取该月的最后一个星期五的日期,例如2020年5月,该月的最后一个星期五为29。

 Example input : may 2020

    output : may 29 2020 , since the last day of may which is 31 falls on weekend

        Example input : june 2020
output : june 30, 2020 , since the last day of june does not fall on weekend

2 个答案:

答案 0 :(得分:0)

从该月的最后一天开始计算天数。如果星期五(dayno = 5)小于5,则减去5,否则加2。如果天数是0或6,则最后从月的最后一天减去天,否则返回月的最后一天。

var calc = function(monthYear) {
    var lastDay = moment(monthYear, "MM-YYYY").endOf("month");
    var lastDayNumber = lastDay.day();
    var daystoSubtract;
    daystoSubtract =
        lastDay.day() >= 5 ?
        (daystoSubtract = lastDayNumber - 5) :
        (daystoSubtract = lastDayNumber + 2);
    if (lastDay.day() === 0 || lastDay.day() === 6) {
        return lastDay.subtract(daystoSubtract, "days");
    } else {
        return lastDay;
    }
};

console.log(calc("05-2020").format("DD-MM-YYYY"));
console.log(calc("06-2020").format("DD-MM-YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

答案 1 :(得分:0)

我的原始javascript版本。

function getVen(_month, _year) {
	
  // Add 1 month for count down on current "_month"
  _year = _month == 12 ? _year + 1 : _year; 
  _month = _month == 12 ? 1 : _month + 1;
  
  // Set Date
	var d = new Date(_month + '/01/' + _year);
  // Remove 1 day
  d.setDate(d.getDate()-1); // Last day of "_month/_year"
  
  // If last day not Saturday nor Sunday
  if (d.getDay() != 6 && d.getDay() != 0) return d;
  
  // Count down looking for day "5"=Friday
	for (var i=7; i>0; i--) {
  	if (d.getDay() == 5) return d;
    d.setDate(d.getDate()-1);
  }
  
  return ''; // Not found ? 
}

document.getElementById('test').innerHTML = getVen(05,2020) + '<br/>';
document.getElementById('test').innerHTML += getVen(06,2020);
<div id="test"></div>

相关问题