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


当前回答

如果您对YYYY-MM-DD格式感到满意,这也可以完成这项工作。

new Date().toISOString().split('T')[0]

2018-03-10

其他回答

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

使用JavaScript内置的Date.pr原型.toLocaleDateString()(MDN文档中有更多选项):

常量选项={月份:'2-位',天:'2位数',年份:'数字',};console.log(newDate().toLocaleDateString('en-US',选项));//年/月/日

我们可以使用具有良好浏览器支持的Intl.DateTimeFormat获得类似的行为。与toLocaleDateString()类似,我们可以传递带有选项的对象:

const date = new Date('Dec 2, 2021') // Thu Dec 16 2021 15:49:39 GMT-0600
const options = {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
}
new Intl.DateTimeFormat('en-US', options).format(date) // '12/02/2021'

最短的答案是:new Date().toJSON().slice(0,10)

使用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;按照您希望的格式。

在澳大利亚,我更喜欢使用此

(new Date()).toISOString().slice(0, 10).split("-").reverse().join("/")