Home > database >  How to convert string into date?
How to convert string into date?

Time:02-22

in my application I want to show the last login of the user. From my backend I get this string: "lastLogin":"2022-02-22T06:02:53.585764600Z". In my frontend, I display it with:

<label >Last visit {{$store.state.user.lastLogin}}</label>

How can I format this string to a date type so I can use methods like .getHours() usw...

CodePudding user response:

// Just pass string to new Date method
const customDate = new Date("2022-02-22T06:02:53.585764600Z");

// Test
console.log(customDate.getHours());

CodePudding user response:

I already found the answer for my problem,

{{Date($store.state.user.lastLogin)}}

Just use this to cast the string inside the brackets

CodePudding user response:

A possible solution is that you can pass the string date from the backend into a Date object. And only then you will be able to use Date methods.

or in your case

{{Date{$store.state.user.lastLogin}}

Please refer to the attached code as a reference.

//Value from DB
const strDate = "2022-02-22T06:02:53.585764600Z";

//Parse the date
const parsedDate = new Date(strDate);

document.querySelector("#display-date").textContent = parsedDate.getHours();
<h1 id="display-date"></h1>

MDN Date docs: Date

W3schools Date Objects

  • Related