2

Beginner javascript learner here, trying to convert an array of strings to an array of dateTimes using just vanilla.

Sample input:

   ["2018-07-16T14:28:03.123", 
    "2018-07-20T14:00:27.123", 
    "2018-07-26T13:31:12.123", 
    "2018-08-12T13:03:37.123", 
    "2018-09-24T12:35:46.123"]

Wanted output:

[2018-07-16T14:28:03.123, 
 2018-07-20T14:00:27.123, 
 2018-07-26T13:31:12.123, 
 2018-08-12T13:03:37.123, 
 2018-09-24T12:35:46.123]

My string values are always dateTime string representations, so I've been trying to leverage new Date(stringDateTime) to convert each string to it's dateTime counterpart, but I'm running into trouble on how to navigate the array and build a new one with the appropriate dateTime data types.

2 Answers 2

3

Use the map function:

var datesStr = ["2018-07-16T14:28:03.123", "2018-07-20T14:00:27.123", "2018-07-26T13:31:12.123", "2018-08-12T13:03:37.123", "2018-09-24T12:35:46.123"]
var dates = datesStr.map(d => new Date(d));
Sign up to request clarification or add additional context in comments.

2 Comments

How would you write the dates variable without the arrow function shorthand?
datesStr.map(function(d) { return new Date(d)})
0

While Igal's answer is more elegant and concise, I would try to show a more basic solution where you use a for loop and new Date():

var stringDates = ["2018-07-16T14:28:03.123", 
    "2018-07-20T14:00:27.123", 
    "2018-07-26T13:31:12.123", 
    "2018-08-12T13:03:37.123", 
    "2018-09-24T12:35:46.123"];

var dateObjects = [];

//Loop over your string array and push dates in your dateObjects array
for (var index in stringDates) {
  var stringDate = stringDates[index];
  dateObjects.push(new Date(stringDate));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.