如何在JavaScript中获取当前日期?
当前回答
不需要图书馆,并且考虑了时区。
因为有时您需要在服务器上进行计算。这可以是独立于服务器时区的。
常量currentTimezoneOffset=8;//UTC+8:00时区,更改Date.prototype.yyyymmdd=函数(){返回[this.getFullYear(),(this.getMonth()+1).toString().padStart(2,“0”),//getMonththis.getDate().toString().padStart(2,“0”)].连接('-');};函数getTodayDateStr(){const d=新日期();//console.log(d);const d2=新日期(d.getTime()+(d.getTimezoneOffset()+currentTimezoneOffset*60)*60*1000);//console.log(d2,d2.yyyymmdd());返回d2.yyyymmdd();}console.log(getTodayDateStr());
其他回答
实现这一点的简单方法(同时考虑到您当前的时区,它利用了ISO yyyy-mm-dd格式)是:
let d = new Date().toISOString().substring(0,19).replace("T"," ") // "2020-02-18 16:41:58"
通常,这是一种非常通用的兼容日期格式,如果需要,可以将其转换为纯日期值:
Date.parse(d); // 1582044297000
如果在“当前日期”之前,你正在考虑“今天”,那么这个技巧可能对你有用:
> 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
干净简单。
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().toISOString().split("T")[0]
输出
[ '2021-02-08', '06:07:44.629Z' ]
如果要使用/format,请使用replaceAll。
new Date().toISOString().split("T")[0].replaceAll("-", "/")
如果您需要其他格式,那么最好使用momentjs。
重要提示:不要使用:var today=new Date();
但是var dateToday=new Date();,例如,var今天没有表示任何内容。