magor
magor

Reputation: 709

Can I create a Date object from a predefined string (typescript)?

I have a value returned in a string (numbers separated by commas) and I'd like to make a Date object out of it. It looks like this is not possible, can someone confirm and/or suggest me a solution.
This does not work :

let dateString='2017,3,22,0';
let dateFromString = new Date(dateString);

This works though (when I pass a list of numbers) :

let dateFromString = new Date(2017,3,22,0);

And this works also :

let dateString = '2008/05/10 12:08:20';
let dateFromString = new Date(dateString);

The goal would be to create a Date object from a uniform string. Is that possible ?

Can I create a Date object from a predefined string, which has only one type of separator (comma, colon, slash or whatever) ?

Upvotes: 1

Views: 495

Answers (1)

Liam Gray
Liam Gray

Reputation: 1129

If your environment is compatible with ES6 (eg. Babel, TypeScript, modern Chrome/Firefox etc), you can use the string's .split(',') and decompose the array into arguments like the following:

const dateString = '2017,3,22,0';
const date = new Date(...dateString.split(','));  // date object for 2017/03/22

ES5 compatible version:

var dateString = '2017,1,2,0';
var date = new (Function.prototype.bind.apply(Date, [null].concat(dateString.split(','))));

As for how the .bind.apply method works with new, you can take a look at Use of .apply() with 'new' operator. Is this possible?

Note: Thanks to the two comments below for spotting my errors 👍

Upvotes: 1

Related Questions