繁体   English   中英

如何使用javascript从新日期动态获取最近三个月的开始日期

[英]how to get the last three month start date dynamically from new date using javascript

从新日期动态获取最近三个月的开始日期,包括当前月份的开始日期,并将其推送到数组中。预期输出为[new Date('09-01-2019'), new Date('08-01-2019'), new Date('07-01-2019'), new Date('06-01-2019')]我的约会[new Date('09-01-2019'), new Date('08-01-2019'), new Date('07-01-2019'), new Date('06-01-2019')]MM-DD-YYYY在javascript中可以吗?

尝试这个:

 let d = new Date(); d.setDate(1); let dteList = [new Date(d.setMonth(d.getMonth())), new Date(d.setMonth(d.getMonth() - 1)), new Date(d.setMonth(d.getMonth() - 1)), new Date(d.setMonth(d.getMonth() - 1))] console.log(dteList); 

new Date('09-01-2019')返回一个Date对象。 在某些实现中,它将表示一个无效的日期。

如果要使用Date对象数组,最好使用值来调用Date构造函数,而不是使用内置的解析器构建字符串。 具有将返回日期数和开始日期的可选参数作为可选参数的函数可能也很有用,例如

 // Return array of n dates from the start date function getLastNMonths(n = 0, d = new Date()) { let y = d.getFullYear(), m = d.getMonth(), dates = []; do { dates.push(new Date(y, m--, 1)); } while (n--); return dates; } console.log('Current month:'); getLastNMonths().forEach(d => console.log(d.toString())); console.log('Current plus prior 6 months:'); getLastNMonths(6).forEach(d => console.log(d.toString())); console.log('1 Jan 2000 plus prior 3 months:'); getLastNMonths(3, new Date(2000,0,1)).forEach(d => console.log(d.toString())); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM