Get String in YYYYMMDD format from JS date object?

后端 未结 30 1849
一个人的身影
一个人的身影 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:47
    new Date('Jun 5 2016').
      toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).
      replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');
    
    // => '2016-06-05'
    
    0 讨论(0)
  • If you don't mind including an additional (but small) library, Sugar.js provides lots of nice functionality for working with dates in JavaScript. To format a date, use the format function:

    new Date().format("{yyyy}{MM}{dd}")
    
    0 讨论(0)
  • 2020-11-22 11:48

    You can simply use This one line code to get date in year

    var date = new Date().getFullYear() + "-" + (parseInt(new Date().getMonth()) + 1) + "-" + new Date().getDate();
    
    0 讨论(0)
  • 2020-11-22 11:48

    It seems that mootools provides Date().format(): https://mootools.net/more/docs/1.6.0/Types/Date

    I'm not sure if it worth including just for this particular task though.

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

    This guy here => http://blog.stevenlevithan.com/archives/date-time-format wrote a format() function for the Javascript's Date object, so it can be used with familiar literal formats.

    If you need full featured Date formatting in your app's Javascript, use it. Otherwise if what you want to do is a one off, then concatenating getYear(), getMonth(), getDay() is probably easiest.

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

    Local time:

    var date = new Date();
    date = date.toJSON().slice(0, 10);
    

    UTC time:

    var date = new Date().toISOString();
    date = date.substring(0, 10);
    

    date will print 2020-06-15 today as i write this.

    toISOString() method returns the date with the ISO standard which is YYYY-MM-DDTHH:mm:ss.sssZ

    The code takes the first 10 characters that we need for a YYYY-MM-DD format.

    If you want format without '-' use:

    var date = new Date();
    date = date.toJSON().slice(0, 10).split`-`.join``;
    

    In .join`` you can add space, dots or whatever you'd like.

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