How to use Date.UTC() In Typescript
In this approach, we are using Date.UTC() to create a UTC timestamp based on the individual components parsed from the input string. The temp array holds the parsed year, month, and day, and a new Date object (res) is then constructed using Date.UTC(). The output Date object displayes the parsed date in Coordinated Universal Time (UTC).
Syntax:
let timestamp: number =
Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]]);
Example: The below example uses Date.UTC() to convert string to date in TypeScript.
let dStr: string = "2024-02-27";
let temp: number[] =
dStr.split('-').map(Number);
let res: Date =
new Date(Date.UTC(temp[0],
temp[1] - 1, temp[2]));
console.log(res);
Output:
2024-02-27T00:00:00.000Z
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