Get String in YYYYMMDD format from JS date object?

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

提交回复
热议问题