Get String in YYYYMMDD format from JS date object?

后端 未结 30 2262
一个人的身影
一个人的身影 2020-11-22 10:47

I\'m trying to use JS to turn a date object into a string in YYYYMMDD format. Is there an easier way than concatenating Date.getYear()

30条回答
  •  余生分开走
    2020-11-22 11:30

    In addition to o-o's answer I'd like to recommend separating logic operations from the return and put them as ternaries in the variables instead.

    Also, use concat() to ensure safe concatenation of variables

    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();
    yyyymmdd:
    yyyymmddhhmm:
    yyyymmddhhmmss:

提交回复
热议问题