Get String in YYYYMMDD format from JS date object?

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

提交回复
热议问题