我正在尝试获取类似于“ 2018-05-17T08:09:02”的垫子的日期,但是当我尝试下面的代码时,我得到的是“ 2018-05-17T8:9:2” 可以帮忙获取“ 2018-05-17T08:09:02”这种格式
let d = new Date();
console.log("date>> "+d.getFullYear() + "-" + ((d.getMonth() + 1) < 10 ? '0' : '') +
(d.getMonth() + 1) + "-" + d.getDate() + "T" +( d.getHours() )+ ":"+ d.getMinutes() + ":"+ d.getSeconds());
答案 0 :(得分:1)
根据How to format numbers by prepending 0 to single-digit numbers?
您理想的答案是
let d = new Date();
console.log("date>> "+d.getFullYear() + "-" + ((d.getMonth() + 1) < 10 ? '0' : '') +
(d.getMonth() + 1) + "-" + d.getDate() + "T" +("0" + d.getHours()).slice(-2)+ ":"+ ("0" + d.getMinutes()).slice(-2) + ":"+ ("0" + d.getSeconds()).slice(-2));
但是正如@Aleksey Solovey在上面已经提到的,我也建议使用d.toISOString().slice(0,-5)
。