简体   繁体   English

如何使用javascript或jquery计算两个日期之间的星期五计数

[英]How to calculate Fridays count between two dates using javascript or jquery

我想要两个日期之间特定日期的总数例如:如果我有一个可变的开始日期和结束日期,那么需要返回这些日期之间星期五的总数。

This might help.这可能会有所帮助。 It's pretty straight forward.这很直接。

 let startDate = new Date('2020-03-08T12:12:06.411Z') let endDate = new Date('2020-03-22T12:12:06.411Z') const givenDay = 5 // 0 for sunday, 1 for monday and so on let numberOfDates = 0 function getDays() { while (startDate < endDate) { if (startDate.getDay() === givenDay) { numberOfDates++ } startDate.setDate( startDate.getDate() + 1 ) } return numberOfDates } console.log(getDays())

You can use this function:您可以使用此功能:

// days is an array of weekdays: 0 is Sunday, ..., 6 is Saturday
const countCertainDays( days, d0, d1 ) {
  var ndays = 1 + Math.round((d1-d0)/(24*3600*1000));
  var sum = function(a,b) {
    return a + Math.floor( (ndays+(d0.getDay()+6-b) % 7 ) / 7 ); };
  return days.reduce(sum,0);
}

example:例子:

countCertainDays([5],new Date(2020,0,1),new Date(2020,2,1))

And another example .另一个例子

Use Moment.js when you're working with dates.在处理日期时使用 Moment.js。

var start = moment('2020-01-01'), //start date
    end   = moment('2020-03-08'), //end date
    day   = 5;

var result = [];
var current = start.clone();

while (current.day(7 + day).isBefore(end)) {
  result.push(current.clone());
}

console.log(result.map(m => m.format('LLLL'))); //result

Read More: https://momentjs.com/阅读更多: https : //momentjs.com/

var start_date = new Date("March 07, 2020 23:15:00");
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

var end_date = new Date("March 07, 2021 23:15:00");    
var next_fri = new Date();
var add_days = 0;
if(start_date.getDay() == 5){
    add_days = 0;
}else if(start_date.getDay() < 5){
    add_days = 5 - start_date.getDay();
}else{
    add_days = start_date.getDay();
}
//set the next friday date from the given start date
next_fri.setDate(start_date.getDate() +  add_days);


var time_gap = (end_date.getTime() - next_fri.getTime());
var time_per_day = 1000 * 24 * 60  * 60;

var days_gap =  Math.floor(time_gap/time_per_day);
var no_fri = Math.floor(days_gap/7);
no_fri = no_fri + 1;


(no_fri is your answer, here i have assumed that end_date is always greater than start_date but if not so you would have to apply the check to inetrchange them)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM