Get String in YYYYMMDD format from JS date object?

后端 未结 30 1775
一个人的身影
一个人的身影 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:25

    // UTC/GMT 0
    document.write('UTC/GMT 0: ' + (new Date()).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812013509
    
    // Client local time
    document.write('<br/>Local time: ' + (new Date(Date.now()-(new Date()).getTimezoneOffset() * 60000)).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812113509

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

    Altered piece of code I often use:

    Date.prototype.yyyymmdd = function() {
      var mm = this.getMonth() + 1; // getMonth() is zero-based
      var dd = this.getDate();
    
      return [this.getFullYear(),
              (mm>9 ? '' : '0') + mm,
              (dd>9 ? '' : '0') + dd
             ].join('');
    };
    
    var date = new Date();
    date.yyyymmdd();
    
    0 讨论(0)
  • 2020-11-22 11:29

    Moment.js could be your friend

    var date = new Date();
    var formattedDate = moment(date).format('YYYYMMDD');
    
    0 讨论(0)
  • 2020-11-22 11:29

    Plain JS (ES5) solution without any possible date jump issues caused by Date.toISOString() printing in UTC:

    var now = new Date();
    var todayUTC = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
    return todayUTC.toISOString().slice(0, 10).replace(/-/g, '');
    

    This in response to @weberste's comment on @Pierre Guilbert's answer.

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

    yyyymmdd=x=>(f=x=>(x<10&&'0')+x,x.getFullYear()+f(x.getMonth()+1)+f(x.getDate()));
    alert(yyyymmdd(new Date));

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

    I didn't like adding to the prototype. An alternative would be:

    var rightNow = new Date();
    var res = rightNow.toISOString().slice(0,10).replace(/-/g,"");
    
    <!-- Next line is for code snippet output only -->
    document.body.innerHTML += res;

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