如何在JavaScript中获取当前日期?


当前回答

这是一个很好的格式化日期

let date=new date().toLocaleDateString(“en”,{年:“numeric”,日:“2位数”,月:“2位”});console.log(日期);

其他回答

TL;博士

只有当您需要本地计算机(客户端)上的当前时间时,这里找到的大多数答案才是正确的,而本地计算机(客户机)是一个通常不可靠的源(它可能与其他系统不同)。

可靠的来源包括:

Web服务器的时钟(但确保已更新)时间API和CDN

细节

在Date实例上调用的方法将返回一个基于计算机本地时间的值。

更多详细信息可以在“MDN web docs”:JavaScript Date对象中找到。

为了方便您,我从他们的文档中添加了一条相关注释:

(…)获取日期和时间或其组件的基本方法都在本地(即主机系统)时区和偏移中工作。

提到这一点的另一个来源是:JavaScript日期和时间对象

需要注意的是,如果某人的时钟关闭了几个小时,或者他们在不同的时区,则Date对象将创建与您自己计算机上创建的时间不同的时间。

您可以使用的一些可靠来源是:

web服务器的时钟(首先检查是否正确设置)时间API和CDN:https://timezonedb.com/apihttp://worldtimeapi.orghttp://worldclockapi.comhttp://www.geonames.org/export/ws-overview.html其他相关API:https://www.programmableweb.com/category/time/api

但是,如果准确度对您的用例并不重要,或者如果您只需要日期与本地机器的时间相关,那么您可以安全地使用Javascript的date基本方法,如date.now()。

试试看:

var currentDate=新日期()var day=currentDate.getDate()var month=currentDate.getMonth()+1var year=currentDate.getFullYear()document.write(“<b>”+天+“/”+月+“/“+年+”</b>”)

结果如下

15/2/2012

要获取日期,则将其内置到JavaScript中:

new Date();

如果您正在寻找日期格式,并且无论如何都在为您的网站使用Kendo jQuery UI库,那么我建议使用内置的Kendo函数:

kendo.toString(new Date(), "yyMMdd"); // Or any other typical date format

有关支持格式的完整列表,请参阅此处。

您可以使用扩展Date对象的Date.js库,因此可以使用.today()方法。

这个答案适用于那些想要一个类似ISO-8601-格式和时区的日期的人。

对于那些不想包含任何日期库的人来说,这是纯JavaScript。

var date = new Date();
var timeZone = date.toString();
// Get timezone ('GMT+0200')
var timeZoneIndex = timeZone.indexOf('GMT');
// Cut optional string after timezone ('(heure de Paris)')
var optionalTimeZoneIndex = timeZone.indexOf('(');
if(optionalTimeZoneIndex != -1){
    timeZone = timeZone.substring(timeZoneIndex, optionalTimeZoneIndex);
}
else{
    timeZone = timeZone.substring(timeZoneIndex);
}
// Get date with JSON format ('2019-01-23T16:28:27.000Z')
var formattedDate = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON();
// Cut ms
formattedDate = formattedDate.substring(0,formattedDate.indexOf('.'));
// Add timezone
formattedDate = formattedDate + ' ' + timeZone;
console.log(formattedDate);

在控制台中打印以下内容:

2019-01-23 17:12:52 GMT+0100

JSFiddle:https://jsfiddle.net/n9mszhjc/4/