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


当前回答

<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/ 

其他回答

这篇文章帮助我写了这个助手,所以我分享它以防有人 正在寻找这个解决方案,它支持yyyy, mm, dd的所有变化

Date.prototype.formattedDate = function (pattern) {
    formattedDate = pattern.replace('yyyy', this.getFullYear().toString());
    var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
    mm = mm.length > 1 ? mm : '0' + mm;
    formattedDate = formattedDate.replace('mm', mm);
    var dd = this.getDate().toString();
    dd = dd.length > 1 ? dd : '0' + dd;
    formattedDate = formattedDate.replace('dd', dd);
    return formattedDate;
};

d = new Date();
pattern = 'yyyymmdd';  // 20150813
d.formattedDate(pattern);

pattern = 'yyyy-mm-dd';
d.formattedDate(pattern); // 2015-08-13

这是一行代码,您可以使用它来创建今天日期的YYYY-MM-DD字符串。

var d = new Date().toISOString().slice(0,10);

Day.js怎么样?

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

https://github.com/iamkun/dayjs

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'
Try this:

函数showdate () {

var a = new Date();
var b = a.getFullYear();
var c = a.getMonth();
(++c < 10)? c = "0" + c : c;
var d = a.getDate();
(d < 10)? d = "0" + d : d;
var final = b + "-" + c + "-" + d; 

return final;


} 

document.getElementById("todays_date").innerHTML = showdate();