-2

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 class="lastVisitLabel">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...

3 Answers3

1

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

// Test
console.log(customDate.getHours());
tarkh
  • 2,424
  • 1
  • 9
  • 12
0

I already found the answer for my problem,

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

Just use this to cast the string inside the brackets

0

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

Mohammed Alwedaei
  • 601
  • 1
  • 7
  • 14