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


当前回答

每次都可以:

var now=新日期();var day=(“0”+now.getDate()).slice(-2);var month=(“0”+(现在.getMonth()+1)).sslice(-2);var today=now.getFullYear()+“-”+(月)+“”+(日);console.log(今天);

其他回答

这个答案适用于那些想要一个类似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/

// Try this simple way

const today = new Date();
let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
console.log(date);

尽可能短。

要获得类似“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().slice(0, 10).split("-").reverse().join("/")

如果在“当前日期”之前,你正在考虑“今天”,那么这个技巧可能对你有用:

> 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

干净简单。