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


当前回答

这做了很多:

var today=新日期();var date=today.getFullYear()+'/'+(today.get-Month()+1)+'/'+today.get date();文档.写入(日期);

其中today.getFullYear()获取当前年份。

today.getMonth()+1获取当前月份。

today.getDate()获取今天的日期。

所有这些都用“/”连接。

其他回答

能够以自定义格式呈现,并在不同地区使用月份名称:

const locale = 'en-us';
const d = new Date(date);

const day = d.getDate();
const month = d.toLocaleString(locale, { month: 'long' });
const year = d.getFullYear();

const time = d.toLocaleString(locale, { hour12: false, hour: 'numeric', minute: 'numeric'});

return `${month} ${day}, ${year} @ ${time}`; // May 5, 2019 @ 23:41

这可能会帮助你

var date = new Date();
console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());

这将以dd/MM/yyyy格式打印当前日期

如果您只需要字符串表示,那么只需使用:

Date();
(function() { var d = new Date(); return new Date(d - d % 86400000); })()

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