如何在JavaScript中获取当前日期?
当前回答
// Try this simple way
const today = new Date();
let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
console.log(date);
其他回答
Date.prototype.toLocalFullDateStringYYYYMMDDHHMMSS = function () {
if (this != null && this != undefined) {
let str = this.getFullYear();
str += "-" + round(this.getMonth() + 1);
str += "-" + round(this.getDate());
str += "T";
str += round(this.getHours());
str += ":" + round(this.getMinutes());
str += ":" + round(this.getSeconds());
return str;
} else {
return this;
}
function round(n){
if(n < 10){
return "0" + n;
}
else return n;
}};
如果您想要对日期格式进行更精细的控制,我强烈建议您查看momentjs。非常棒的图书馆-只有5KB。http://momentjs.com/
如果您正在使用jQuery。试试这一行:
$.datepicker.formatDate('dd/mm/yy', new Date());
以下是格式化日期的惯例
d-月份的日期(无前导零)dd-月份的日期(两位数)o-一年中的某一天(无前导零)oo-一年中的一天(三位数)D-天名称缩写DD-日名称长m-一年中的月份(无前导零)mm-一年中的月份(两位数)M-月名缩写MM-月份名称长y-年(两位数)yy-年(四位数)
以下是jQuery日期选择器的参考
我的解决方案使用字符串文字。了解更多信息。。。
//声明日期为dvar d=新日期()//日期的内联格式const exampleOne=`${d.getDay()}-${d.getMonth()+1}-${d.getFullYear()}`//一月为0,因此需要+1//使用特征线和运算符常量示例二=`+++++++++++带换行符和算术运算符示例新行上的年份:${d.getFullYear()}年份减(-)30年:${d.getFullYear()-30}你明白了。。。+++++++++++`console.log('============')console.log(示例一)console.log('============')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/