如何在JavaScript中获取当前日期?
当前回答
尽可能短。
要获得类似“2018-08-03”的格式:
let today=new Date().toISOString().slice(0,10)console.log(今天)
要获得类似“8/3/2018”的格式:
let today=new Date().toLocaleDateString()console.log(今天)
此外,还可以将locale作为参数传递,例如传递给LocaleDateString(“sr”)等。
其他回答
大多数其他答案都提供了日期和时间。如果你只需要日期。
new Date().toISOString().split("T")[0]
输出
[ '2021-02-08', '06:07:44.629Z' ]
如果要使用/format,请使用replaceAll。
new Date().toISOString().split("T")[0].replaceAll("-", "/")
如果您需要其他格式,那么最好使用momentjs。
我认为这是一个老问题,但最简单的方法是:
var date = new Date();
var TimeStamp = date.toLocaleString();
function CurrentTime(){
alert(TimeStamp);
}
这将获取当前时间,根据位置将其传递给字符串,然后您可以调用函数CurrentTime来显示时间。对我来说,这将是获取时间戳的最有效方法。
重要提示:不要使用:var today=new Date();
但是var dateToday=new Date();,例如,var今天没有表示任何内容。
如果在“当前日期”之前,你正在考虑“今天”,那么这个技巧可能对你有用:
> 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
干净简单。
那么多复杂的答案。。。
只需使用new Date(),如果需要它作为字符串,只需使用newDate().toISOString()
享受