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


当前回答

您可以使用扩展Date对象的Date.js库,因此可以使用.today()方法。

其他回答

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

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

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

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

Try

`${Date()}`.slice(4,15)

console.log(`${Date()}`.slice(4,15))

这里我们使用标准的JS功能:模板文本、转换为字符串的Date对象和切片。这可能是满足OP要求的最短解决方案(没有时间,只有日期)

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

您可以使用moment.js:http://momentjs.com/

var m=moment().格式(“DD/MM/YYYY”);文件.写入(m);<script src=“https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js“></script>

使用new Date()生成包含当前日期和时间的新Date对象。

var today=新日期();var dd=字符串(today.getDate()).padStart(2,'0');var mm=字符串(today.getMonth()+1).padStart(2,'0')//一月是0!var yyyy=today.getFullYear();今天=mm+'/'+dd+'/'+yyyy;document.write(今天);

这将以mm/dd/yyyy的格式显示今天的日期。

只需更改今天=mm+'/'+dd+'/'+yyyy;按照您希望的格式。