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


当前回答

// utc / gmt 0 文档。write('UTC/GMT 0: ' + (new Date()). toisostring()。片(0,19)。替换(/ [^ 0 - 9]/ g, " "));/ / 20150812013509 //客户端本地时间 文档。write('<br/>本地时间:' + (new Date(Date.now()-(new Date()). gettimezoneoffset () * 60000)). toisostring()。片(0,19)。替换(/ [^ 0 - 9]/ g, " "));/ / 20150812113509

其他回答

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

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

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

使用padStart:

Date.prototype.yyyymmdd = function() {
    return [
        this.getFullYear(),
        (this.getMonth()+1).toString().padStart(2, '0'), // getMonth() is zero-based
        this.getDate().toString().padStart(2, '0')
    ].join('-');
};
<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/ 

另一种方法是使用toLocaleDateString与一个具有大端日期格式标准的地区,如瑞典,立陶宛,匈牙利,韩国,…:

date.toLocaleDateString('se')

删除分隔符(-)只是替换非数字的问题:

登录(新日期)。代表(/ / / D/g, ');

这不会像UTC日期格式那样产生潜在错误:与本地时区的日期相比,UTC日期可能相差一天。