我试图使用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/ 

其他回答

很好,很简单:

    var date = new Date();
    var yyyy = date.getFullYear();
    var mm = date.getMonth() + 1; // getMonth() is zero-based
    if (mm < 10) mm='0'+mm;
    var dd = date.getDate();
    if (dd < 10) dd='0'+dd;
    /*date.yyyymmdd();*/

    console.log('test - '+yyyy+'-'+mm+'-'+dd);
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'

如果你不介意包含一个额外的(但很小的)库,Sugar.js为在JavaScript中处理日期提供了很多不错的功能。 格式化日期,使用format函数:

new Date().format("{yyyy}{MM}{dd}")

以下是对https://stackoverflow.com/users/318563/o-o的回答的一点改进

Date.prototype.ddmmyyyy = function(delimiter) {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
    var dd  = this.getDate().toString();
    return (dd[1]?dd:"0"+dd[0]) + delimiter + (mm[1]?mm:"0"+mm[0]) + delimiter +yyyy  ; // padding
};

希望对大家有所帮助!

:)

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();