Making JavaScript Date Object From String Using Split And Map
I have a javascript string, I split it into the numbers for the Date object and then convert to numbers using map. Date isn't liking the format when it is parsed and mapped. This
Solution 1:
The JavaScript Date constructor accepts one of the following:
- No parameters, returning a Date object with the current date;
- A date string
- Unix Timestamp in Millisseconds (
Date.now()
is a good example) - A sequence of arguments, in the following format:
year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]
In your situation, no manipulation of the string is necessary. Just using this block of code below solves the problem:
var timeString = '2016-01-01T17:44:32';
var dateTime = new Date( timeString );
console.log(dateTime.getTime()); // 1451670272000
Solution 2:
it's simple, to pass any Array elements to a constructor as arguments all you have to do is generate a new constructor with your intended array.
try this :
var timeString = '2016-01-01T17:44:32';
// now generate new Date Constructor loaded with you array arguments
var arrComponents = timeString.split(/T|:|-/).map(Number);
var newDateConstuctor = Date.bind.apply(Date,arrComponents);
var dateTime = new newDateConstuctor();
Post a Comment for "Making JavaScript Date Object From String Using Split And Map"