Skip to content Skip to sidebar Skip to footer

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 = newDate( 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 argumentsvar arrComponents = timeString.split(/T|:|-/).map(Number);
var newDateConstuctor = Date.bind.apply(Date,arrComponents);

var dateTime = newnewDateConstuctor();

Post a Comment for "Making Javascript Date Object From String Using Split And Map"