0

I'm trying to convert unix timestamp to local date in a react project. Below is the function that I'm using:

function convertDate(unixDate) {
        const d = new Date(unixDate * 1000);
        const day = d.toLocaleString(d.getDate())
        return(day);
    }

The date I'm getting is not acurate. For example is we run convertDate(1657745369979.82) we should get the date '07/13/2022 8:49:29 PM'. However the date that I'm actually getting is '11/10/54501, 8:59:39 AM'

Baslki
  • 63
  • 1
  • 1
  • 9

2 Answers2

0

Why are you multiplying by 1000 ? This works just fine

new Date(1657745369979.82).toLocaleString() => '14/07/2022, 02:19:29'

which is the same as

Convert epoch to human-readable date and vice versa
1657745369979.82
 Timestamp to Human date  [batch convert]
Supports Unix timestamps in seconds, milliseconds, microseconds and nanoseconds.
Assuming that this timestamp is in milliseconds:
GMT: Wednesday, July 13, 2022 8:49:29.979 PM
Your time zone: Thursday, July 14, 2022 2:19:29.979 AM GMT+05:30
Relative: A day ago
 

from https://www.epochconverter.com/

If there's more that you want, this old thread should also help Convert a Unix timestamp to time in JavaScript

g.p
  • 312
  • 1
  • 5
  • Thank you. This works fine in the console, but in my react app, I get "Invalid Date" when I remove *1000 – Baslki Jul 15 '22 at 06:21
  • Interesting.. i tried this on a react app and it worked fine
    {`${new Date(1657745369979.82).toLocaleString()}`}
    Maybe you are fetching the date from an api and its not formatted properly
    – g.p Jul 15 '22 at 07:09
  • I've found a solution although I have no idea why it works. return new Date(unixDate * 1).toLocaleString() multiplying the date by 1 makes it work for some reason. – Baslki Jul 15 '22 at 07:18
0

It looks like you do not need to multiply the timestamp by 1000.

Unix timestamps are often of this length: 1657831769, which would need to be multiplied by 1000 (https://www.epochconverter.com/ is useful for testing conversions).

const unixDate = 1657745369979.82;
const d = new Date(unixDate);
console.log(d.toISOString());

Output: 2022-07-13T20:49:29.979Z

Steve
  • 111
  • 9
  • Thank you. This works fine in the console, but in my react app, I get "Invalid Date" when I remove *1000. Could it be because the unix date I'm getting is 13 digits instead of 10? – Baslki Jul 15 '22 at 06:25
  • Sorry, I'm no expert in react, could be worth trying to remove the decimal places? E.g., 1657745369979 instead of 1657745369979.82 – Steve Jul 15 '22 at 06:30