I'm trying to convert Firebase timestamp to local date without success.
I'm getting Invalid Date
with the code below. What am I doing wrong with toLocaleString
or is there other methods?
<Table.Header>
<Table.Column>Email</Table.Column>
<Table.Column>Last login</Table.Column>
<Table.Column>Created</Table.Column>
</Table.Header>
<Table.Body>
{usersList.map((user, index) => (
<Table.Row key={index}>
<Table.Cell>{user.user.email}</Table.Cell>
<Table.Cell>{new Date(user.user.lastLoginAt).toLocaleString("da-DK", {year: "numeric", month: "long", day: "numeric", hour: "2-digit", minute: "2-digit",})}</Table.Cell>
<Table.Cell>{new Date(user.user.createdAt).toLocaleString("da-DK", {year: "numeric", month: "long", day: "numeric", hour: "2-digit", minute: "2-digit",})}</Table.Cell>
</Table.Row>
))}
</Table.Body>
CodePudding user response:
The issue occurs because both lastLoginAt
and createdAt
values come as strings from your API data. You need to convert them to a number so they can be used inside the new Date()
call.
new Date(Number(user.user.lastLoginAt))
new Date(Number(user.user.createdAt))
The Date
constructor expects the timestamp value to be a number.
Time value or timestamp number
value
An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most UNIX Timestamp functions are only accurate to the nearest second.