var range = getDates(new Date(), new Date().addDays(7));
我希望“range”成为一个日期对象的数组,其中包括两个日期之间每一天的日期。关键是它还应该处理月份和年份的边界。var range = getDates(new Date(), new Date().addDays(7));
我希望“range”成为一个日期对象的数组,其中包括两个日期之间每一天的日期。关键是它还应该处理月份和年份的边界。npm i moment
然后在你的文件中导入它
var moment = require("moment");
然后使用以下代码获取两个日期之间的所有日期列表:
let dates = [];
let currDate = moment.utc(new Date("06/30/2019")).startOf("day");
let lastDate = moment.utc(new Date("07/30/2019")).startOf("day");
do {
dates.push(currDate.clone().toDate());
} while (currDate.add(1, "days").diff(lastDate) < 0);
dates.push(currDate.clone().toDate());
console.log(dates);
/**
* Returns array of working days between two dates.
*
* @param {string} startDate
* The start date in yyyy-mm-dd format.
* @param {string} endDate
* The end date in yyyy-mm-dd format.
* @param {boolean} onlyWorkingDays
* If true only working days are returned. Default: false
*
* @return {array}
* Array of dates in yyyy-mm-dd string format.
*/
function getDates(startDate, stopDate, onlyWorkingDays) {
let doWd = typeof onlyWorkingDays ==='undefined' ? false : onlyWorkingDays;
let dateArray = [];
let dayNr;
let runDateObj = moment(startDate);
let stopDateObj = moment(stopDate);
while (runDateObj <= stopDateObj) {
dayNr = runDateObj.day();
if (!doWd || (dayNr>0 && dayNr<6)) {
dateArray.push(moment(runDateObj).format('YYYY-MM-DD'));
}
runDateObj = moment(runDateObj).add(1, 'days');
}
return dateArray;
}
这是我喜欢的做法
// hours * minutes * seconds * milliseconds
const DAY_IN_MS = 24 * 60 * 60 * 1000
/**
* Get range of dates
* @param {Date} startDate
* @param {Number} numOfDays
* @returns {array}
*/
const dateRange = (startDate, numOfDays) => {
const startDateMs = startDate.getTime()
// get array of days and map it to Date object
return [...Array(numOfDays).keys()].map(i => new Date(startDateMs + i * DAY_IN_MS))
}
d3js提供了许多方便的函数,包括d3.time以便于进行日期操作。
" 针对您的具体请求:UTC
var range = d3.utcDay.range(new Date(), d3.utcDay.offset(new Date(), 7));
var range = d3.timeDay.range(new Date(), d3.timeDay.offset(new Date(), 7));
const startDate = moment();
_.range(0, 7).map((d) => startDate.clone().add(d, 'day').toDate())
Generate an array of years:
const DAYS = () => {
const days = []
const dateStart = moment()
const dateEnd = moment().add(30, ‘days')
while (dateEnd.diff(dateStart, ‘days') >= 0) {
days.push(dateStart.format(‘D'))
dateStart.add(1, ‘days')
}
return days
}
console.log(DAYS())
Generate an arrays for month:
const MONTHS = () => {
const months = []
const dateStart = moment()
const dateEnd = moment().add(12, ‘month')
while (dateEnd.diff(dateStart, ‘months') >= 0) {
months.push(dateStart.format(‘M'))
dateStart.add(1, ‘month')
}
return months
}
console.log(MONTHS())
Generate an arrays for days:
const DAYS = () => {
const days = []
const dateStart = moment()
const dateEnd = moment().add(30, ‘days')
while (dateEnd.diff(dateStart, ‘days') >= 0) {
days.push(dateStart.format(‘D'))
dateStart.add(1, ‘days')
}
return days
}
console.log(DAYS())
注意:我知道这与所请求的解决方案略有不同,但我认为许多人会发现它很有用。
如果您想在两个日期之间找到每个“x”间隔(天,月,年等),moment.js和moment-range扩展包可以实现此功能。
例如,要查找两个日期之间的每30天:
window['moment-range'].extendMoment(moment);
var dateString = "2018-05-12 17:32:34.874-08";
var start = new Date(dateString);
var end = new Date();
var range1 = moment.range(start, end);
var arrayOfIntervalDates = Array.from(range1.by('day', { step: 30 }));
arrayOfIntervalDates.map(function(intervalDate){
console.log(intervalDate.format('YY-M-DD'))
});
var from_date = '2016-01-01';
var to_date = '2016-02-20';
var dates = getDates(from_date, to_date);
console.log(dates);
function getDates(from_date, to_date) {
var current_date = new Date(from_date);
var end_date = new Date(to_date);
var getTimeDiff = Math.abs(current_date.getTime() - end_date.getTime());
var date_range = Math.ceil(getTimeDiff / (1000 * 3600 * 24)) + 1 ;
var weekday = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
var dates = new Array();
for (var i = 0; i <= date_range; i++) {
var getDate, getMonth = '';
if(current_date.getDate() < 10) { getDate = ('0'+ current_date.getDate());}
else{getDate = current_date.getDate();}
if(current_date.getMonth() < 9) { getMonth = ('0'+ (current_date.getMonth()+1));}
else{getMonth = current_date.getMonth();}
var row_date = {day: getDate, month: getMonth, year: current_date.getFullYear()};
var fmt_date = {weekDay: weekday[current_date.getDay()], date: getDate, month: months[current_date.getMonth()]};
var is_weekend = false;
if (current_date.getDay() == 0 || current_date.getDay() == 6) {
is_weekend = true;
}
dates.push({row_date: row_date, fmt_date: fmt_date, is_weekend: is_weekend});
current_date.setDate(current_date.getDate() + 1);
}
return dates;
}
https://gist.github.com/pranid/3c78f36253cbbc6a41a859c5d718f362.js
map()
方法返回的内容即可。const moment = require('moment');
// ...
/**
* @param {string|import('moment').Moment} start
* @param {string|import('moment').Moment} end
* @returns {import('moment').Moment[]}
*/
const getDateRange = (start, end) => {
const s = moment.isMoment(start) ? start : moment(start);
const e = moment.isMoment(end) ? end : moment(end);
return [...Array(1 + e.diff(s, 'days')).keys()].map(n => moment(s).add(n, 'days'));
};
功能:
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};
使用方法:
var dates = getDatesRange(new Date(2019,01,01), new Date(2019,01,25));
dates.forEach(function(date) {
console.log(date);
});
eachDayOfInterval
[1]和addDays
[2]来返回开始日期和结束日期之间的日期数组。 - tinystone