最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Parse array of Date strings Date array in Javascript - Stack Overflow

programmeradmin4浏览0评论

I am receiving this JSON object:

response.myDates = [ "2017-11-19T00:00:00.000Z", "2017-12-08T00:00:00.000Z", "2017-12-25T00:00:00.000Z", "2017-12-31T00:00:00.000Z", "2018-01-01T00:00:00.000Z" ]

I would like to save all these dates (actually there are hundreds of them) in a Date array parsedDates in Javascript.

Is there a simple way to do it without a while loop?

I am receiving this JSON object:

response.myDates = [ "2017-11-19T00:00:00.000Z", "2017-12-08T00:00:00.000Z", "2017-12-25T00:00:00.000Z", "2017-12-31T00:00:00.000Z", "2018-01-01T00:00:00.000Z" ]

I would like to save all these dates (actually there are hundreds of them) in a Date array parsedDates in Javascript.

Is there a simple way to do it without a while loop?

Share Improve this question asked Nov 9, 2017 at 10:50 user411103user411103 11
  • 6 response.myDates.map(Date) – gurvinder372 Commented Nov 9, 2017 at 10:52
  • 1 @musefan or simply you can use map – Muthu Kumaran Commented Nov 9, 2017 at 10:56
  • 1 @musefan I bet map uses but not OP going to write a loop for this. – Muthu Kumaran Commented Nov 9, 2017 at 10:59
  • 1 @gurvinder372: That doesn't work, see here – musefan Commented Nov 9, 2017 at 11:00
  • 2 @MuthuKumaran: Sometime you have to criticise to help. If someone is doing something wrong do you not tell them they are wrong? Would you just say "well done, keep doing that wrong thing you are doing". Yes, people often don't like criticism and they get in a huff about it, but they end up better off for it in the long run. – musefan Commented Nov 9, 2017 at 11:04
 |  Show 6 more ments

2 Answers 2

Reset to default 10

You can simple do a map to new Date();

let results = response.myDates.map(date => new Date(date))

Just map over your array :

const myDates = [ "2017-11-19T00:00:00.000Z", "2017-12-08T00:00:00.000Z"],
      datesArray = myDates.map( dateString => new Date(dateString) )
      
console.log(datesArray)

Note :

Surprisingly, this Stackoverflow snippet outputs an array of strings (not sure why), but if you run it in your Chrome console or in Codepen, it outputs an array of dates, as it should

发布评论

评论列表(0)

  1. 暂无评论