Home > Software engineering >  Convert Unix Date and Time to Local Time with JavaScript (React)
Convert Unix Date and Time to Local Time with JavaScript (React)

Time:07-16

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'

CodePudding user response:

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

CodePudding user response:

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

  • Related