如何在JavaScript中获取当前日期?


当前回答

Date.prototype.toLocalFullDateStringYYYYMMDDHHMMSS = function () {
if (this != null && this != undefined) {
    let str = this.getFullYear();
    str += "-" + round(this.getMonth() + 1);
    str += "-" + round(this.getDate());
    str += "T";
    str += round(this.getHours());
    str += ":" + round(this.getMinutes());
    str += ":" + round(this.getSeconds());
    return str;
} else {
    return this;
}

function round(n){
    if(n < 10){
        return "0" + n;
    }
    else return n;
}};

其他回答

var date = new Date().toLocaleDateString("en-US");

此外,您可以使用两个参数调用方法toLocaleDateString:

var date = new Date().toLocaleDateString("en-US", {
    "year": "numeric",
    "month": "numeric"
});

有关MDN上此方法的详细信息。

这可能会帮助你

var date = new Date();
console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());

这将以dd/MM/yyyy格式打印当前日期

实现这一点的简单方法(同时考虑到您当前的时区,它利用了ISO yyyy-mm-dd格式)是:

let d = new Date().toISOString().substring(0,19).replace("T"," ") // "2020-02-18 16:41:58"

通常,这是一种非常通用的兼容日期格式,如果需要,可以将其转换为纯日期值:

Date.parse(d); // 1582044297000
new Date().toISOString().slice(0,10); 

也会起作用

那么多复杂的答案。。。

只需使用new Date(),如果需要它作为字符串,只需使用newDate().toISOString()

享受