我正在尝试创建一个函数,该函数将创建一个以6位数字表示的日期列表,从今天开始到2018年8月。结果应该是这样的:
[190322, 190321, 190320, ...]
我不确定是否有内置的方法可以获取这种6位数字的日期?
答案 0 :(得分:2)
没有内置“一个功能就可以完成”的功能,可以立即获得结果。
但是,您可以使用提供的功能getFullYear
,getMonth
和getDate
来获得结果:
let d = new Date()
let formatted = d.getFullYear().toString().slice(2,4) +
(d.getMonth()+1 > 10 ? d.getMonth()+1 : `0${d.getMonth()+1}`) +
(d.getDate() > 10 ? d.getDate() : `0${d.getDate()}`)-0
让我们逐行通过
// Uses the getFullYear function which will return 2019, ...
d.getFullYear().toString().slice(2,4) // "19"
// getMonth returns 0-11 so we have to add one month,
// since you want the leading zero we need to also
// check for the length before adding it to the string
(d.getMonth()+1 < 10 ? d.getMonth()+1 : `0${d.getMonth()+1}`) // "03"
// uses getDate as it returns the date number; getDay would
// result in a the index of the weekday
(d.getDate() < 10 ? d.getDate() : `0${d.getDate()}`) // "22"
// will magically convert the string "190322" into an integer 190322
-0
值得一说的是,这是一种快速的“实现方法”,无需安装任何npm软件包,但请确保自己涵盖一些极端情况,因为涉及到日期时很多。
另一种选择是使用toISOString
并使用split,一些正则表达式和slice来接收结果:
d.toISOString().split('T')[0].replace(/\-/g, '').slice(2,8)-0
逐步获取输出:
d.toISOString() // "2019-03-22T22:13:12.975Z"
d.toISOString().split('T') // (2) ["2019-03-22", "22:13:12.975Z"]
d.toISOString().split('T')[0] // "2019-03-22"
d.toISOString().split('T')[0].replace(/\-/g, '') // "20190322"
d.toISOString().split('T')[0].replace(/\-/g, '').slice(2,8) // "190322"
d.toISOString().split('T')[0].replace(/\-/g, '').slice(2,8)-0 // 190322
答案 1 :(得分:1)
在Date
个对象的协助下,您可以像这样进行操作:
function getDateNumsBetween(a, b) {
// b should come before a
a = new Date(a); // new instance to avoid side effects.
const result = [];
while (a >= b) {
result.push(((a.getFullYear()%100)*100 + a.getMonth()+1)*100 + a.getDate());
a.setDate(a.getDate()-1);
}
return result;
}
const result = getDateNumsBetween(new Date(), new Date("August 1, 2018"));
console.log(result);