如何在JavaScript中获取当前日期?
当前回答
不需要图书馆,并且考虑了时区。
因为有时您需要在服务器上进行计算。这可以是独立于服务器时区的。
常量currentTimezoneOffset=8;//UTC+8:00时区,更改Date.prototype.yyyymmdd=函数(){返回[this.getFullYear(),(this.getMonth()+1).toString().padStart(2,“0”),//getMonththis.getDate().toString().padStart(2,“0”)].连接('-');};函数getTodayDateStr(){const d=新日期();//console.log(d);const d2=新日期(d.getTime()+(d.getTimezoneOffset()+currentTimezoneOffset*60)*60*1000);//console.log(d2,d2.yyyymmdd());返回d2.yyyymmdd();}console.log(getTodayDateStr());
其他回答
如果您只需要字符串表示,那么只需使用:
Date();
如果您正在使用jQuery。试试这一行:
$.datepicker.formatDate('dd/mm/yy', new Date());
以下是格式化日期的惯例
d-月份的日期(无前导零)dd-月份的日期(两位数)o-一年中的某一天(无前导零)oo-一年中的一天(三位数)D-天名称缩写DD-日名称长m-一年中的月份(无前导零)mm-一年中的月份(两位数)M-月名缩写MM-月份名称长y-年(两位数)yy-年(四位数)
以下是jQuery日期选择器的参考
(function() { var d = new Date(); return new Date(d - d % 86400000); })()
尽可能短。
要获得类似“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”)等。
var d=(new Date()).toString().split('').spling(1,3).join('');文档.写入(d)
要将其分解为步骤:
(new Date()).toString()给出“2013年6月28日星期五15:30:18 GMT-0700(PDT)”(new Date()).toString().split(“”)将上述字符串除以每个空格,并返回一个数组,如下所示:[“Fri”,“Jun”,”28“,”2013“,”15:31:14“,”GMT-0700“,”(PDT)“](new Date()).toString().split('').spling(1,3).join('')从上述数组中获取第二、第三和第四个值,用空格将它们连接起来,并返回字符串“Jun 28 2013”