我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?


当前回答

Day.js怎么样?

它只有2KB,你还可以使用dayjs().format('YYYY-MM-DD')。

https://github.com/iamkun/dayjs

其他回答

我试图写一个简单的库操作JavaScript日期对象。你可以试试这个。

var dateString = timeSolver.getString(date, "YYYYMMDD")

Libarary: https://github.com/sean1093/timeSolver

这段代码修复了Pierre Guilbert的答案:

(10000年后依然有效)

YYYYMMDD=new Date().toISOString().slice(0,new Date().toISOString().indexOf("T")).replace(/-/g,"")

我不喜欢增加原型。另一种选择是:

var rightNow = new Date(); var res = rightNow.toISOString().slice(0,10).replace(/-/g,""); <!——下一行仅用于代码段输出——> document.body.innerHTML += res;

<pre>Date.prototype.getFromFormat = function(format) {
    var yyyy = this.getFullYear().toString();
    format = format.replace(/yyyy/g, yyyy)
    var mm = (this.getMonth()+1).toString(); 
    format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
    var dd  = this.getDate().toString();
    format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
    var hh = this.getHours().toString();
    format = format.replace(/hh/g, (hh[1]?hh:"0"+hh[0]));
    var ii = this.getMinutes().toString();
    format = format.replace(/ii/g, (ii[1]?ii:"0"+ii[0]));
    var ss  = this.getSeconds().toString();
    format = format.replace(/ss/g, (ss[1]?ss:"0"+ss[0]));
    var ampm = (hh >= 12) ? "PM" : "AM";
    format = format.replace(/ampm/g, (ampm[1]?ampm:"0"+ampm[0]));
    return format;
};
var time_var = $('#899_TIME');
var myVar = setInterval(myTimer, 1000);
function myTimer() {
    var d = new Date(); 
    var date = d.getFromFormat('dd-mm-yyyy hh:ii:ss:ampm');
    time_var.text(date);

} </pre>

use the code and get the output like **26-07-2017 12:29:34:PM**

check the below link for your reference

https://parthiban037.wordpress.com/2017/07/26/date-and-time-format-in-oracle-apex-using-javascript/ 
new Date('Jun 5 2016').
  toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).
  replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');

// => '2016-06-05'