是否有内置的方式以6位数字格式获得日期



我正在尝试创建一个函数。从今天到2018年8月开始,将创建6位数字格式的日期列表。结果应该是这样的:

[190322, 190321, 190320, ...]

我不确定是否有建筑物是一种以这种6位格式获得日期的方法?

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);

"一个函数都可以做"以立即获得结果。

选项1:

但是,您可以使用提供的功能getFullYeargetMonthgetDate来获得您的结果:

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

让我们逐行通过IT

// 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软件包,但请确保自己涵盖边缘案例,因为约会时有很多。

选项2:

另一个选择是去 toISOString并使用拆分,一点正则罚款,并切成薄片以接收您的结果:

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

最新更新