1

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

4
  • what is your actual problem? Commented Mar 28, 2017 at 14:11
  • updated question. can i create a date object from a predefined string which uses only one character as separator ? Commented Mar 28, 2017 at 14:14
  • And what exactly uniform string do you want to use - 2017,3,22,0 or 2008/05/10 12:08:20? Commented Mar 28, 2017 at 14:14
  • I want to avoid using , and : both as separator. I would like to use only one certain character as separator, either ,, : or / or whatever. Commented Mar 28, 2017 at 14:17

1 Answer 1

1

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 👍

Sign up to request clarification or add additional context in comments.

7 Comments

const is not compatible with ES5
It should be new (Function.prototype.bind.apply(Date, [null].concat(dateString.split(','))))
Thanks hindmost and abhishekkannojia 👍
I am actually using Typescript + Angular2 and the compiler will compile to ES5...unfortunatelly both of the suggested options are failing. I know I could parse the string and pass to Date what it needs, I was just wondering if there is a simple solution like using split().
How is it failing? The TypeScript compilation, or type checking? It appears to compile fine on typescriptlang.org/play
|

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.