Mike J
Mike J

Reputation: 159

Converting an array of strings to an array of dateTimes

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.

Upvotes: 2

Views: 1952

Answers (2)

Mariyan
Mariyan

Reputation: 664

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));
}

Upvotes: 0

Igal S.
Igal S.

Reputation: 14534

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));

Upvotes: 3

Related Questions