jQuery 获取两个日期之间的所有日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18109481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get all the dates that fall between two dates
提问by patricko
i have a problem where the user selects a range of dates. i need to then find out what dates fall between those two selected dates. they're coming in via jquery with something as simple as
我遇到用户选择日期范围的问题。然后我需要找出这两个选定日期之间的日期。他们是通过 jquery 进来的,就像这样简单
$('#from').val()+"-"+$('#to').val();
$('#from').val()+"-"+$('#to').val();
they're coming from jqueryUI datepicker and they just look like
它们来自 jqueryUI datepicker,它们看起来像
08/07/2013 - 08/09/2012
08/07/2013 - 08/09/2012
but i can't figure out how to step through the dates and determine which days in in between. i need the specific dates, but this becomes really complicated with things like the end of the month and different number of days in each month. in this specific example, i'd need to get
但我不知道如何逐步完成日期并确定中间的哪几天。我需要具体的日期,但这会因为月末和每个月不同的天数而变得非常复杂。在这个特定的例子中,我需要得到
08/07/2013, 08/08/2013, 08/09/2013
08/07/2013, 08/08/2013, 08/09/2013
回答by cfs
You can grab the values from your date pickers using the getDate
method, since this will return you a Date object. Then, starting at the start date increment "current" date by 1 day and add it to an array until the current date is the same as the end date.
您可以使用该getDate
方法从日期选择器中获取值,因为这将返回一个 Date 对象。然后,从开始日期开始将“当前”日期增加 1 天并将其添加到数组中,直到当前日期与结束日期相同。
Note that you'll need to create a new Date() when adding it to the between
array, or else you will just be referencing the currentDate
object and all your values will be the same.
请注意,在将它添加到between
数组时,您需要创建一个新的 Date() ,否则您将只是引用该currentDate
对象,并且您的所有值都将相同。
var start = $("#from").datepicker("getDate"),
end = $("#to").datepicker("getDate"),
currentDate = new Date(start.getTime()),
between = []
;
while (currentDate <= end) {
between.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
回答by Pec1983
//start of with getting the dates from your array
var between =[]
for (var i = 0; i < arrayOfHolsInfoTbl.length; i++){
alert( holsInfoTblData[i].StartDate)
alert(holsInfoTblData[i].EndStart)
var datePickedStr1 = holsInfoTblData[i].StartDate;
var datePickedDate1 = new Date(datePickedStr1)//converts string to date object
var datePickedStr2 = holsInfoTblData[i].EndStart;
var datePickedDate2 = new Date(datePickedStr1)
while (datePickedDate1 <= datePickedDate2) {
between.push(new Date(datePickedDate1));
datePickedDate1.setDate(datePickedDate1.getDate() + 1);
}
}
//loop through array and print all dates that have been added to array
for (var j = 0; j < between.length; j++) {
alert("This is all the dates " + between[j])
}