How to use new Date() In Typescript
In this approach, we are using the new Date() constructor in TypeScript to convert a string representation into a Date object. The output Date object represents the date and time parsed from the input string, and it is then printed to the console.
Syntax:
let currentDate: Date = new Date();
Example: The below example uses new Date() to convert string to date in TypeScript.
let dStr: string = "2024-02-27";
let res: Date = new Date(dStr);
console.log(res, typeof res);
Output:
2024-02-27T00:00:00.000Z object
How to Convert String to Date in TypeScript ?
In TypeScript, conversion from string to date can be done using the Date object and its method.
We can use various inbuilt methods of Date object like new Date() constructor, Date.parse(), and Date.UTC.
Table of Content
- Using new Date()
- Using Date.parse()
- Using Date.UTC()
- Using the moment.js library
Contact Us