3 ways to convert a string to date in TypeScript:
In this post, we will learn how to convert a string to date in TypeScript in three different ways. String-to-date conversion is an important part of most JavaScript or TypeScript projects. If we convert a string to a date, we can make other operations on the date object.
There are different ways in JavaScript and TypeScript to convert a string to date. We can directly do the conversion or we can use other third-party libraries like momemnt.js or date-fns to do that.
Method 1: String to date in TypeScript by using the Date constructor:
We can use the Date constructor to create a Date
object. The 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- Starting from the third argument, it optionally takes a year, month, day etc. to create the
Date
. All values start from 0 except for theday
which starts from 1.
To convert a string
to a Date
, we can use the second constructor i.e. new Date(dateString)
.
Let’s take a look at the below example:
const firstDate = new Date('December 20, 2020 10:30:00')
const secondDate = new Date('2020-12-20T10:30:00')
const thirdDate = new Date('2020-12-20')
const 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:
2020-12-20T05:00:00.000Z
2020-12-20T05:00:00.000Z
2020-12-20T00:00:00.000Z
Invalid Date
The fourth example failed as the provided string is not valid.
Method 2: Convert a string to Date by using the momentjs package in TypeScript:
momentjs is a popular library used for handling different date-time operations. We can use this library in JavaScript or TypeScript. We can specify the format of the date that we are parsing and it will parse that string to a moment
object. We can use the toDate()
method to convert a moment
object to a Date
.
You can use npm
or yarn
to install it to your project:
npm i moment
# or
yarn add moment
We can use it once it is installed:
import moment from "moment";
const strDate = "14-04-2023 03:02:03";
const date = moment(strDate, "DD-MM-yyyy hh:mm:ss").toDate();
console.log(`Date: ${date}`);
- It parsed the date from the string strDate. We need to use the
toDate()
function to convert the parsed moment object to aDate
.
Method 3: Convert a string to Date in TypeScript with date-fns:
date-fns is another library used for date manipulation in JavaScript/TypeScript. It is available as an npm package. It has different functions available for different date-related operations. To use this library, you need to add it to your project using npm
or yarn
:
npm i date-fns
# or
yarn add date-fns
Once it is done, you can import and use it in your project:
import { parse } from "date-fns";
const strDate = "04-04-2023";
const date = parse(strDate, "dd-MM-yyyy", new Date());
console.log(`Date: ${date.toISOString()}`);
The parse
method is used to parse a date. We are passing MM-dd-yyyy
as the formatting pattern. It returns the parsed date object.
We can also change the pattern to read the time component as well:
import { parse } from "date-fns";
const strDate = "14-04-2023 03:02:03+00";
const date = parse(strDate, "dd-MM-yyyy hh:mm:ssx", new Date());
console.log(`Date: ${date.toISOString()}`);
It will print:
Date: 2023-04-14T03:02:03.000Z
You can go through their doc to understand different formatting patterns.
date-fns
is faster than moment
. If you are just starting to add a date manipulation library to your project, you can go with date-fns
.