Javascript - 获取两个日期之间的日期数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4413590/
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
Javascript - get array of dates between 2 dates
提问by Scott Klarenbach
var range = getDates(new Date(), new Date().addDays(7));
I'd like "range" to be an array of date objects, one for each day between the two dates.
我希望“范围”是一组日期对象,两个日期之间的每一天都有一个。
The trick is that it should handle month and year boundaries as well.
诀窍是它也应该处理月份和年份的界限。
采纳答案by Scott Klarenbach
function (startDate, endDate, addFn, interval) {
addFn = addFn || Date.prototype.addDays;
interval = interval || 1;
var retVal = [];
var current = new Date(startDate);
while (current <= endDate) {
retVal.push(new Date(current));
current = addFn.call(current, interval);
}
return retVal;
}
回答by John Hartsock
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getDates(startDate, stopDate) {
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= stopDate) {
dateArray.push(new Date (currentDate));
currentDate = currentDate.addDays(1);
}
return dateArray;
}
Here is a functional demohttp://jsfiddle.net/jfhartsock/cM3ZU/
回答by Mohammed Safeer
Try this, remember to include moment js,
试试这个,记得包含moment js,
function getDates(startDate, stopDate) {
var dateArray = [];
var currentDate = moment(startDate);
var stopDate = moment(stopDate);
while (currentDate <= stopDate) {
dateArray.push( moment(currentDate).format('YYYY-MM-DD') )
currentDate = moment(currentDate).add(1, 'days');
}
return dateArray;
}
回答by enesn
I looked all the ones above. Ended up writing myself. You do not need momentjs for this. A native for loop is enoughand makes most sense because a for loop exists to count values in a range.
我看了上面所有的。自己写完了。为此,您不需要 momentjs。原生 for 循环就足够了并且最有意义,因为存在 for 循环来计算范围内的值。
One Liner:
一个班轮:
var getDaysArray = function(s,e) {for(var a=[],d=new Date(s);d<=e;d.setDate(d.getDate()+1)){ a.push(new Date(d));}return a;};
Long Version
长版
var getDaysArray = function(start, end) {
for(var arr=[],dt=new Date(start); dt<=end; dt.setDate(dt.getDate()+1)){
arr.push(new Date(dt));
}
return arr;
};
List dates in between:
列出介于两者之间的日期:
var daylist = getDaysArray(new Date("2018-05-01"),new Date("2018-07-01"));
daylist.map((v)=>v.toISOString().slice(0,10)).join("")
/*
Output:
"2018-05-01
2018-05-02
2018-05-03
...
2018-06-30
2018-07-01"
*/
Days from a past date until now:
从过去日期到现在的天数:
var daylist = getDaysArray(new Date("2018-05-01"),new Date());
daylist.map((v)=>v.toISOString().slice(0,10)).join("")
回答by Ahmed Aswani
I use moment.jsand Twix.jsthey provide a very great support for date and time manpulation
我使用moment.js和Twix.js它们为日期和时间操作提供了非常好的支持
var itr = moment.twix(new Date('2012-01-15'),new Date('2012-01-20')).iterate("days");
var range=[];
while(itr.hasNext()){
range.push(itr.next().toDate())
}
console.log(range);
I have this running on http://jsfiddle.net/Lkzg1bxb/
回答by Phrogz
var boxingDay = new Date("12/26/2010");
var nextWeek = boxingDay*1 + 7*24*3600*1000;
function getDates( d1, d2 ){
var oneDay = 24*3600*1000;
for (var d=[],ms=d1*1,last=d2*1;ms<last;ms+=oneDay){
d.push( new Date(ms) );
}
return d;
}
getDates( boxingDay, nextWeek ).join("\n");
// Sun Dec 26 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Mon Dec 27 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Tue Dec 28 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Wed Dec 29 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Thu Dec 30 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Fri Dec 31 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Sat Jan 01 2011 00:00:00 GMT-0700 (Mountain Standard Time)
回答by Akrion
If you are using moment then you can use their "official plugin" for ranges moment-range
and then this becomes trivial.
如果您使用的是 moment,那么您可以将他们的“官方插件”用于范围moment-range
,然后这变得微不足道。
moment-range node example:
矩范围节点示例:
const Moment = require('moment');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);
const start = new Date("11/30/2018"), end = new Date("09/30/2019")
const range = moment.range(moment(start), moment(end));
console.log(Array.from(range.by('day')))
moment-range browser example:
瞬间范围浏览器示例:
window['moment-range'].extendMoment(moment);
const start = new Date("11/30/2018"), end = new Date("09/30/2019")
const range = moment.range(moment(start), moment(end));
console.log(Array.from(range.by('day')))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/4.0.1/moment-range.js"></script>
date fns example:
日期 fns 示例:
If you are using date-fns
then eachDay
is your friend and you get by far the shortest and most concise answer:
如果您正在使用date-fns
theneachDay
是您的朋友,那么您会得到迄今为止最短和最简洁的答案:
console.log(dateFns.eachDay(
new Date(2018, 11, 30),
new Date(2019, 30, 09)
))
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>
回答by Irfy
Just came across this question, the easiest way to do this is using moment:
刚刚遇到这个问题,最简单的方法是使用时刻:
You need to install moment and moment-range first:
您需要先安装 moment 和 moment-range:
const Moment = require('moment');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);
const start = moment()
const end = moment().add(2, 'months')
const range = moment.range(start, end)
const arrayOfDates = Array.from(range.by('days'))
console.log(arrayOfDates)
回答by digiguru
Using ES6 you have Array.from meaning you can write a really elegant function, that allows for dynamic Intervals (hours, days, months).
使用 ES6 你有 Array.from 意味着你可以编写一个非常优雅的函数,它允许动态间隔(小时、天、月)。
function getDates(startDate, endDate, interval) {
const duration = endDate - startDate;
const steps = duration / interval;
return Array.from({length: steps+1}, (v,i) => new Date(startDate.valueOf() + (interval * i)));
}
const startDate = new Date(2017,12,30);
const endDate = new Date(2018,1,3);
const dayInterval = 1000 * 60 * 60 * 24; // 1 day
const halfDayInterval = 1000 * 60 * 60 * 12; // 1/2 day
console.log("Days", getDates(startDate, endDate, dayInterval));
console.log("Half Days", getDates(startDate, endDate, halfDayInterval));
回答by Adrian Moisa
I have been using @Mohammed Safeer solution for a while and I made a few improvements. Using formated dates is a bad practice while working in your controllers. moment().format()
should be used only for display purposes in views. Also remember that moment().clone()
ensures separation from input parameters, meaning that the input dates are not altered. I strongly encourage you to use moment.js when working with dates.
我一直在使用@Mohammed Safeer 解决方案一段时间,我做了一些改进。在控制器中工作时,使用格式化的日期是一种不好的做法。moment().format()
应该仅用于视图中的显示目的。还要记住,moment().clone()
确保与输入参数分离,这意味着输入日期不会改变。我强烈建议您在处理日期时使用 moment.js。
Usage:
用法:
- Provide moment.js dates as values for
startDate
,endDate
parameters interval
parameter is optional and defaults to 'days'. Use intervals suported by.add()
method (moment.js). More details heretotal
parameter is useful when specifying intervals in minutes. It defaults to 1.
- 提供 moment.js 日期作为
startDate
,endDate
参数的值 interval
参数是可选的,默认为“天”。使用.add()
方法支持的间隔(moment.js)。更多细节在这里total
参数在以分钟为单位指定间隔时很有用。它默认为 1。
Invoke:
调用:
var startDate = moment(),
endDate = moment().add(1, 'days');
getDatesRangeArray(startDate, endDate, 'minutes', 30);
Function:
功能:
var getDatesRangeArray = function (startDate, endDate, interval, total) {
var config = {
interval: interval || 'days',
total: total || 1
},
dateArray = [],
currentDate = startDate.clone();
while (currentDate < endDate) {
dateArray.push(currentDate);
currentDate = currentDate.clone().add(config.total, config.interval);
}
return dateArray;
};