如何在JavaScript中计算2个日期之间的日期名称

如何在JavaScript中计算2个日期之间的日期名称

本文介绍了如何在JavaScript中计算2个日期之间的日期名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个日期提醒者和周日的复选框列表。用户可以选择开始日期或结束日期,并检查任何复选日。我想计算2天之前的
星期的数量。

I have 2 datepickers and a list of checkboxes of week days. A user can select a start date or end date and check any checkbox day. I want to count the number ofweek days between 2 days.

例如:我想加入任何瑜伽课程,然后我将选择开始或结束日期并选择星期一,星期二,星期二。

For example: I want to join any yoga classes then I will select start or end date and also select week day like Monday , Tuesday .

现在我想计算2个日期之间的所有星期一和星期二的数量

Now i want to count the number of all Mondays and Tuesdays between 2 dates

 date1 = Mar 01,2016
 date2 = Apr 01,2016

我想计算这些日期之间的日期名称,如下所示:

I want to count number of day name between these date like this:

我试过这个代码

var d           = new Date(date1);
var now         = new Date(Date.now());
var daysOfYear  = [];
count           = 0;
for (d ; d <= date1 ; d.setDate(d.getDate() + 1)) {
  val = $("#ch_"+d.getDay());
  if(val.is(':checked')){
    count++;
  }
}

但是它给出了一个 TypeError :d.getDay不是一个函数

推荐答案

你需要在日期之间迭代并检查一天

You need to iterate between dates and check the day

首先将日期转换为日期对象

First convert the dates into a date object

date1 = convertToDateObj(date1); //assuming you already have a way to parse this string to date
date2 = convertToDateObj(date2); //assuming you already have a way to parse this string to date

现在迭代他们

var dayCount = {0:0,1:0,2:0,3:0,4:0,5:0,6:0}; //0 is sunday and 6 is saturday
for (var d = date1; d <= date2; d.setDate(d.getDate() + 1))
{
    dayCount[d.getDay()]++;
}
console.log(dayCount);

这篇关于如何在JavaScript中计算2个日期之间的日期名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 15:19