How to convert string to date in typescript

How to convert a string to date in typescript:

In this post, we will learn how to convert a string to date in typescript. String to date conversion is an important part in most JavaScript or TypeScript applications. If we convert a string to a date, we can make other operations on date objects.

JavaScript and TypeScript makes it easy to convert a string to date. We can directly do the conversion or we can use other third-party libraries like momemnt.js to do that.

String to date in typescript:

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]]]]])

Here,

  • 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

Using momentjs:

momentjs is a popular library used for handling date-time. We can use this library in javascript or typescript. We can specify the format of the date that we are parsing and also we can specify the format we need for the output.

For example:

let parsedDate = moment(dateStr,"YYYY-MM-DD");
let outputDate = parsedDate.format("DD-MM-YYYY");

Here,

  • 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.

You might also like: