如何在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;
}};

其他回答

更清洁、更简单的版本:

new Date().toLocaleString();

结果因用户的语言环境而异:

2017年2月27日上午9:15:41

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

这做了很多:

var today=新日期();var date=today.getFullYear()+'/'+(today.get-Month()+1)+'/'+today.get date();文档.写入(日期);

其中today.getFullYear()获取当前年份。

today.getMonth()+1获取当前月份。

today.getDate()获取今天的日期。

所有这些都用“/”连接。

能够以自定义格式呈现,并在不同地区使用月份名称:

const locale = 'en-us';
const d = new Date(date);

const day = d.getDate();
const month = d.toLocaleString(locale, { month: 'long' });
const year = d.getFullYear();

const time = d.toLocaleString(locale, { hour12: false, hour: 'numeric', minute: 'numeric'});

return `${month} ${day}, ${year} @ ${time}`; // May 5, 2019 @ 23:41

试试看:

var currentDate=新日期()var day=currentDate.getDate()var month=currentDate.getMonth()+1var year=currentDate.getFullYear()document.write(“<b>”+天+“/”+月+“/“+年+”</b>”)

结果如下

15/2/2012