moment.js扩展库moment-range.js
Fancy date ranges for Moment.js
const moment = require('moment'); const MomentRange = require('moment-range'); MomentRange.extendMoment(moment); const range = moment.range('2014-11-01', '2015-02-01'); // 月份 let months = Array.from(range.by('month')).map( month => month.format('YYYY-MM-DD') ); console.log(months); // [ '2014-11-01', '2014-12-01', '2015-01-01', '2015-02-01' ] // 年份 const years = Array.from(range.by('year')).map( month => month.year() ); console.log(years); // [ 2014 ] // 星期 const weeks = Array.from(range.by('week')).map( month => [ month.startOf('week').format('YYYY-MM-DD'), month.endOf('week').format('YYYY-MM-DD'), ] ); console.log(weeks); // [ [ '2014-10-26', '2014-11-01' ], // [ '2014-11-02', '2014-11-08' ], // [ '2014-11-09', '2014-11-15' ], // [ '2014-11-16', '2014-11-22' ], // [ '2014-11-23', '2014-11-29' ], // [ '2014-11-30', '2014-12-06' ], // [ '2014-12-07', '2014-12-13' ], // [ '2014-12-14', '2014-12-20' ], // [ '2014-12-21', '2014-12-27' ], // [ '2014-12-28', '2015-01-03' ], // [ '2015-01-04', '2015-01-10' ], // [ '2015-01-11', '2015-01-17' ], // [ '2015-01-18', '2015-01-24' ], // [ '2015-01-25', '2015-01-31' ] // ] // 季度 const quarters = Array.from(range.by('quarter')).map( month => month.format('[Q]Q') ); console.log(quarters); //[ 'Q4', 'Q1' ]