如何在JavaScript中获取当前日期?
当前回答
如果您希望格式化为字符串。
statusUpdate = "time " + new Date(Date.now()).toLocaleTimeString();
输出:“时间11:30:53 AM”
其他回答
您可以使用扩展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/
如果您正在使用jQuery。试试这一行:
$.datepicker.formatDate('dd/mm/yy', new Date());
以下是格式化日期的惯例
d-月份的日期(无前导零)dd-月份的日期(两位数)o-一年中的某一天(无前导零)oo-一年中的一天(三位数)D-天名称缩写DD-日名称长m-一年中的月份(无前导零)mm-一年中的月份(两位数)M-月名缩写MM-月份名称长y-年(两位数)yy-年(四位数)
以下是jQuery日期选择器的参考
var utc=new Date().toJSON().slice(0,10).replace(/-/g,'/');文档.写入(utc);
如果要重用utc变量,例如new Date(utc),请使用替换选项,因为Firefox和Safari无法识别带破折号的日期。
能够以自定义格式呈现,并在不同地区使用月份名称:
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