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


当前回答

Moment.js可以成为你的朋友

var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');

其他回答

除了o-o的答案之外,我还建议将逻辑操作与返回值分离,并将它们作为三元放入变量中。

另外,使用concat()来确保变量的安全连接

Date.prototype.yyyymmdd = function() { var yyyy = this.getFullYear(); var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based var dd = this.getDate() < 10 ? "0" + this.getDate() : this.getDate(); return "".concat(yyyy).concat(mm).concat(dd); }; Date.prototype.yyyymmddhhmm = function() { var yyyymmdd = this.yyyymmdd(); var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours(); var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes(); return "".concat(yyyymmdd).concat(hh).concat(min); }; Date.prototype.yyyymmddhhmmss = function() { var yyyymmddhhmm = this.yyyymmddhhmm(); var ss = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds(); return "".concat(yyyymmddhhmm).concat(ss); }; var d = new Date(); document.getElementById("a").innerHTML = d.yyyymmdd(); document.getElementById("b").innerHTML = d.yyyymmddhhmm(); document.getElementById("c").innerHTML = d.yyyymmddhhmmss(); <div> yyyymmdd: <span id="a"></span> </div> <div> yyyymmddhhmm: <span id="b"></span> </div> <div> yyyymmddhhmmss: <span id="c"></span> </div>

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

原生Javascript:

new Date().toLocaleString('zu-ZA').slice(0,10).replace(/-/g,'');

回答另一个简单性和可读性的问题。 此外,不鼓励使用新方法编辑现有的预定义类成员:

function getDateInYYYYMMDD() {
    let currentDate = new Date();

    // year
    let yyyy = '' + currentDate.getFullYear();

    // month
    let mm = ('0' + (currentDate.getMonth() + 1));  // prepend 0 // +1 is because Jan is 0
    mm = mm.substr(mm.length - 2);                  // take last 2 chars

    // day
    let dd = ('0' + currentDate.getDate());         // prepend 0
    dd = dd.substr(dd.length - 2);                  // take last 2 chars

    return yyyy + "" + mm + "" + dd;
}

var currentDateYYYYMMDD = getDateInYYYYMMDD();
console.log('currentDateYYYYMMDD: ' + currentDateYYYYMMDD);

很好,很简单:

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