MomentJs: How to convert string to date in Typescript?

Protagonist picture Protagonist · Feb 28, 2017 · Viewed 36.6k times · Source

Im implementing Ag Gird in Angular 2. I have a date column and sorting of dates and Ag grid expects type of date in the format only. Thus I had to send it in the form of date for rendering. But my input is string. I have my dateString in the format 2017-01-19. I'm doing

let myDate:Date = moment(dateString).toDate();

But it's givimg me output as Thu Jan 19 2017 00:00 Indian Standard Time. I tried like this too

let myDate:Date = moment(dateString).format("DD/MM/YYYY");

This gives me error- string is not assignable to Date.

Tried like this too

let myDate:Date = moment(dateString,"DD/MM/YYYY");

But no luck. What I want is, type of the output as date and in the form 19-01-2017

Please suggest

Answer

Wissam picture Wissam · Feb 28, 2017

Try this:

let myDate:Date = moment(dateString,"YYYY-MM-DD").format("DD-MM-YYYY");

Basically, when you call moment(), you should specify the format your current date is in, not the output format that you want. The output format should be specified when calling .format().