Home > Software design >  How to convert a string to a date in angular
How to convert a string to a date in angular

Time:06-11

How to covert a string to a date in Angular13?

For example: str = '2022-06-09T22:00:00Z'; to a datetime mm/dd/yyyy --:-- --

CodePudding user response:

If you are okay with using a library, I would recommend to use moment.js. Here's a link!

Firstly, since we can not access the inbuilt functions from a string, we need to convert it to a date:

var date = new Date("2022-06-09T22:00:00Z")

Using moment.js:

moment.utc(d).format('MM/DD/YYYY HH:mm:ss')     // -> 06/09/2022 22:00:00

Using standard in-built functions:

var formatted = ("0" (d.getUTCMonth() 1)).slice(-2)   "/"   ("0"   d.getUTCDate()).slice(-2)   "/"   d.getUTCFullYear()   " "   ("0"   d.getUTCHours()).slice(-2)   ":"   ("0"   d.getUTCMinutes()).slice(-2)   ":"   ("0"   d.getUTCSeconds()).slice(-2);

If you don't want the time in UTC, you can simply puzzle it around to remove it.

CodePudding user response:

new Date("2022-06-09T22:00:00Z")

CodePudding user response:

You can use angular pipe date

<span>{{ str | date: 'mm/dd/yyyy h:mm:ss' }}</span>

StackBlitz

  • Related