Get String in YYYYMMDD format from JS date object?

后端 未结 30 1777
一个人的身影
一个人的身影 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();
    <div>
      yyyymmdd: <span id="a"></span>
    </div>
    <div>
      yyyymmddhhmm: <span id="b"></span>
    </div>
    <div>
      yyyymmddhhmmss: <span id="c"></span>
    </div>

    0 讨论(0)
  • 2020-11-22 11:31

    Another way is to use toLocaleDateString with a locale that has a big-endian date format standard, such as Sweden, Lithuania, Hungary, South Korea, ...:

    date.toLocaleDateString('se')
    

    To remove the delimiters (-) is just a matter of replacing the non-digits:

    console.log( new Date().toLocaleDateString('se').replace(/\D/g, '') );

    This does not have the potential error you can get with UTC date formats: the UTC date may be one day off compared to the date in the local time zone.

    0 讨论(0)
  • 2020-11-22 11:32

    This is a single line of code that you can use to create a YYYY-MM-DD string of today's date.

    var d = new Date().toISOString().slice(0,10);
    
    0 讨论(0)
  • 2020-11-22 11:32

    date-shortcode to the rescue!

    const dateShortcode = require('date-shortcode')
    dateShortcode.parse('{YYYYMMDD}', new Date())
    //=> '20180304'
    
    0 讨论(0)
  • 2020-11-22 11:33

    Answering another for Simplicity & readability.
    Also, editing existing predefined class members with new methods is not encouraged:

    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);
    
    0 讨论(0)
  • 2020-11-22 11:34

    dateformat is a very used package.

    How to use:

    Download and install dateformat from NPM. Require it in your module:

    const dateFormat = require('dateformat');

    and then just format your stuff:

    const myYYYYmmddDate = dateformat(new Date(), 'yyyy-mm-dd');

    0 讨论(0)
提交回复
热议问题