如何在JavaScript中获取当前日期?
当前回答
如果在“当前日期”之前,你正在考虑“今天”,那么这个技巧可能对你有用:
> new Date(3600000*Math.floor(Date.now()/3600000))
2020-05-07T07:00:00.000Z
这样,您将获得时间为0:00:00的日期实例。
操作原理很简单:我们获取当前时间戳,并将其除以1天,以毫秒表示。我们会得到一个分数。通过使用Math.floor,我们去掉了分数,所以我们得到了一个整数。现在,如果我们将它乘以一天(同样是以毫秒为单位),我们会得到一个日期时间戳,时间恰好在一天的开始。
> now = Date.now()
1588837459929
> daysInMs = now/3600000
441343.73886916664
> justDays = Math.floor(daysInMs)
441343
> today = justDays*3600000
1588834800000
> new Date(today)
2020-05-07T07:00:00.000Z
干净简单。
其他回答
var date = new Date().toLocaleDateString("en-US");
此外,您可以使用两个参数调用方法toLocaleDateString:
var date = new Date().toLocaleDateString("en-US", {
"year": "numeric",
"month": "numeric"
});
有关MDN上此方法的详细信息。
使用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'
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(),如果需要它作为字符串,只需使用newDate().toISOString()
享受
如果您只想要一个没有时间信息的日期,请使用:
var today=新日期();today.setHours(0,0,0);document.write(今天);