Reputation: 6266
I have been looking at the momentjs momenjs documentation because I want to use it to return a date object from a date that is a string in a particular format. My code looks like this.
const date = moment(stringDate, 'YYYY-MM-DD HH:MM:SS');
console.log(date);
But it creates an invalid date as can be seen here.
What am I doing wrong. How can I get a date object from a date string that is in a particular format?
Upvotes: 0
Views: 308
Reputation: 1074989
You're using MM:SS
for minutes:seconds, but it should be mm:ss
; details here.
Example:
const stringDate = "2018-05-11 14:25:37";
// Parsing
const m = moment(stringDate, 'YYYY-MM-DD HH:mm:ss');
// Show it in a different format to demonstrate parsing worked
console.log(m.format("DD/MM/YYYY HH:mm"));
// Accessing the underlying Date object
const dt = m.toDate();
// Log that dateobject
console.log(dt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
Upvotes: 2
Reputation: 2181
In order to parse a string then return a different format you can:
> moment(dateString).format('DD.MM.YYYY')
Further examples: Official docs: https://momentjs.com/docs/ Other sources: https://coderwall.com/p/vc3msa/a-very-short-introduction-to-moment-js
Upvotes: 0