如何在JavaScript中获取当前日期?
当前回答
能够以自定义格式呈现,并在不同地区使用月份名称:
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
其他回答
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;
}};
这是一个很好的格式化日期
let date=new date().toLocaleDateString(“en”,{年:“numeric”,日:“2位数”,月:“2位”});console.log(日期);
(function() { var d = new Date(); return new Date(d - d % 86400000); })()
更清洁、更简单的版本:
new Date().toLocaleString();
结果因用户的语言环境而异:
2017年2月27日上午9:15:41
如果您只想要一个没有时间信息的日期,请使用:
var today=新日期();today.setHours(0,0,0);document.write(今天);