1

How to covert a string to a date in Angular13?

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

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Moment.js will be deprecated
0
new Date("2022-06-09T22:00:00Z")

Comments

0

You can use angular pipe date

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

StackBlitz

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.