Date object from string in dd:MM:yyyy format


#1

Hi, i got problem in my with converting date string into date object. I get date string from backend in dd:MM:yyyy hh:MM:ss format. Is there any easy way to create date object out of it? When i use new Date() and this string from backend, it creates wrong object with days and months switched. Any ideas?


#2

Use Moment.js. When it comes to date the package is just so much better

First, run the command

npm install moment --save

Then, on the page that you want to use moment, import the library with

import Moment from 'moment'

From there, any date String u have (let say sth like dd:MM:yyyy), you can just convert it to a javascript date object with

let dateString = "22-04-2017"; //whatever date string u have
let dateObject = moment(dateString, "DD-MM-YYYY").toDate();

Could be a long step, but momentJS is such a flexible tool to calculate date difference, to add/minus days/hours/weeks and converting between string, moment and date object is so convenient that i stick with it


#3

or use https://date-fns.org/ which is lighter than momentjs


#4

or if you could modify your backend, why not not transmiting date as string but as time (numeric) values

new Date().getTime()

#5

Dang…Thanks for letting me know of a lighter alternative for date management in JS~


#6

No worries, both libs have their own advantages :wink:


#7

Thx for answers, i solved it by changing the format in backend. But these solutions seems good too :smiley: Question is which way is more elegant :slight_smile: