获取时间区间
/**
* 获取指定类型的开始和结束时间, 默认为当前时间所属类型的开始和结束时间
* @param {String} type 类型: 'year', 'month', 'day'
* @param {Number} before 当前时间的前 n 天/月/年(type), 如果传值大于0, 则开始时间为当前时间减去 n(before) 天/月/年(type)后所属类型的开始时间而结束时间为当前时间减去 1 天/月/年(type)后所属类型的结束时间
*/
getDateRange = (type, before = 0) => {
return {
start: before ? moment().subtract(before, type).startOf(type).format() : moment().startOf(type).format(),
end: before ? moment().subtract(1, type).endOf(type).format() : moment().endOf(type).format()
};
};
getDateRange('month', 6) -- 获取当前时间的前 6个月的开始和结束时间
getDateRange('month') -- 获取当前月的开始和结束时间
getDateRange('year') -- 获取当年的开始和结束时间
根据结束时间获取所属月的开始时间
/**
* 根据结束时间获取所属月的开始时间
* @param {String} type 类型: 'year', 'month', 'day'
* @param {Number} before
*/
static getMonthStartByEnd(type, before = 0) {
const end = moment().subtract(before, type).endOf(type).format();
const start = moment(end).startOf('month').format();
return {
start,
end
}
}
获取指定时间距离当前多少天
getDiffDays = (date) => {
const end = moment(date);
return moment().diff(end, 'day');
};
getDiffDays('2021-06-11') - 0
getDiffDays('2021-06-10') - 1
获取指定时间范围内的每个月
const dateRange = getDateRange('month', 6);
const start = moment(dateRange.start);
const end = moment(dateRange.end);
const diff = end.diff(start, 'month');
let months = [];
_.times(diff + 1, i => {
let startMonth = moment(start);
months.push(startMonth.add(i, "months").format("YYYY-MM"));
});
console.log(months)