MomentJs: How to convert string to date in Typescript?
Solution 1
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()
.
Solution 2
moment().toDate();
gives a Date object
got the answer from Moment.js transform to date object
Protagonist
Updated on July 09, 2022Comments
-
Protagonist almost 2 years
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
-
Heretic Monkey about 7 yearsThat won't work because
myDate
is set to be a Date type. This is essentially the same as the second piece of code the OP has. -
Protagonist about 7 yearsThere is a problem here. If I do export to excel, it will contain {{params.value | date:'d MMM'}}, not the original date. I got this info from Ag-grid doc
-
Christopher Moore about 7 yearsYou didn't mention anything about exporting to Excel in your question. If that is what you want working (it's an enterprise feature), you will have to resort to another option
-
Protagonist about 7 yearsMy bad, yes I'm using enterprise trial version. Please do let me know if there is a workaround for this. Many thanks
-
Wissam about 7 yearsIt's not exactly the same piece of code because in his example, he doesn't specify the date's format when trying to convert it to a moment object.
-
Heretic Monkey about 7 yearsWhich is why I didn't say "exactly the same"; I said "essentially" the same, and it will still fail with the same error.