Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

jquery - get all the dates that fall between two dates

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

$('#from').val()+"-"+$('#to').val();

they're coming from jqueryUI datepicker and they just look like

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

Working Demo

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...