如何在JavaScript中获取当前日期?
当前回答
如果您希望对日期格式进行更精细的控制,我强烈建议您查看日期FNS。
它是一个很棒的库,比Moment.js小得多。它是一种基于函数的方法,比其他基于类的库更快。它提供了迄今为止所需的大量操作。
其他回答
var dateTimeToday = new Date();
var dateToday = new Date(
dateTimeToday.getFullYear(),
(dateTimeToday.getMonth() + 1) /*Jan = 0! */,
dateTimeToday.getDate(),
0,
0,
0,
0);
new Date().toDateString();
结果:
“2016年2月3日星期三”
Varun的答案不考虑TimezoneOffset。以下是一个版本:
var d = new Date()
new Date(d.getTime() - d.getTimezoneOffset() * 60000).toJSON().slice(0, 10) // 2015-08-11
TimezoneOffset是分钟,而Date构造函数需要毫秒,因此乘以60000。
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();
console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());
这将以dd/MM/yyyy格式打印当前日期