We can use the date constructor to create a Date object. Following are the available constructors:
new Date(value) new Date(dateString) new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
- value is the timestamp number. It is the number of milliseconds since Jan 1, 1970, 00:00:00: UTC.
- dateString is a date in string format which should be in IETF-complaint RFC 2822 timestamps
- The third one takes year, month day etc. to create a Date. All values are starts from 0 except for date.
To convert a string to date, we can use the second one i.e. new Date(dateString).
Let’s take a look at the below example:
let firstDate = new Date('December 20, 2020 10:30:00') let secondDate = new Date('2020-12-20T10:30:00') let thirdDate = new Date('2020-12-20') let fourthDate = new Date('20th December, 2020') console.log(firstDate) console.log(secondDate) console.log(thirdDate) console.log(fourthDate)
It will parse the strings successfully for firstDate, secondDate, and thirdDate but it will fail for fourthDate.
It will print output as like below:
2020-12-20T05:00:00.000Z 2020-12-20T05:00:00.000Z 2020-12-20T00:00:00.000Z Invalid Date
let parsedDate = moment(dateStr,"YYYY-MM-DD"); let outputDate = parsedDate.format("DD-MM-YYYY");
- It parsed the date from the string dateStr and kept the value in parsedDate. The format we are specifying here is the format of the dateStr.
- The format method formates the parsed date to the output format that we need.