Convert Unix Date and Time to Local Time with JavaScript (React) - javascript

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'

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

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

Convert unix time to local iso time format to set in htmk date time picker

So, I have a unix time as
endingTime= 1669060881
and then I do this to convert it into ISO format
this.edate = new Date(endingTime*1000).toISOString() ===> 2022-11-21T20:01:21.000Z
slicing it so that it can fir html local date input
this.edate = this.edate.slice(0, -8) ===> 2022-11-21T20:01
and then patch this value in my date time picker of form
this.userForm['endingTime']['controls'].patchValue(this.edate);
html
---> shows result as 21-11-22 and 8:01 as the time
when I put the time 1669060881 in here https://www.epochconverter.com/
you can see two times
GMT: Monday, November 21, 2022 8:01:21 PM
Your time zone: Tuesday, November 22, 2022 1:31:21 AM GMT+05:30
I need the iso conversiton in "Your time zone" time but currentt edate val is the GMT timezone
pls help
You can use toLocaleString instead of toISOString
Date.toLocaleString
const ms = 1669060881 * 1000
const dateTime = new Date(ms).toLocaleString()
console.log(dateTime)
Don't re-invent the wheel and use some popular and well tested library when working with dates. Like zonedTimeToUtc from date-fns-tz.
const dateTime = zonedTimeToUtc(ms, 'Your timezone')

How to parse UNIX timestamps with luxon?

I tried to use the luxon library to move away from moment - to translate the 1615065599.426264 timestamp into an ISO date.
According to the Online Epoch Converter this corresponds to
GMT: Saturday, March 6, 2021 9:19:59.426 PM
Your time zone: Saturday, March 6, 2021 10:19:59.426 PM GMT+01:00
Relative: 3 days ago
Removing the decimal part gives the same result.
The code using luxon:
let timestamp = 1615065599.426264
console.log(luxon.DateTime.fromMillis(Math.trunc(timestamp)).toISO())
console.log(luxon.DateTime.fromMillis(timestamp).toISO())
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>
This result is
1970-01-19T17:37:45.599+01:00
1970-01-19T17:37:45.599+01:00
It is suspiciously close to Unix Epoch (1970-01-01 00:00:00).
Where is my mistake?
Luxon can accept UNIX / epoch times in seconds with the .fromSeconds() function. You can then use the .toISO() function to output an ISO format.
in your specific example:
const { DateTime } = require('luxon')
//your other code here
const myDateTime = DateTime.fromSeconds(1615065599.426264)
const myDateTimeISO = myDateTime.toISO()
//outputs '2021-03-07T08:19:59.426+11:00'
ref: https://moment.github.io/luxon/#/parsing?id=unix-timestamps
So called "Unix time" counts the number of seconds since 01.01.1970 whereas Luxon (and most things JavaScript) expects a value with a millisecond resolution.
Multiplying your value by 1000 will yield the expected result:
> let timestamp = 1615065599.426264
undefined
> new Date(timestamp).toJSON()
'1970-01-19T16:37:45.599Z'
> new Date(timestamp * 1000).toJSON()
'2021-03-06T21:19:59.426Z'

Convert a given unix time string (EST) to local server time (CST) and evaluate difference between unix time and current time

I have been struggling with comparing between two date/times using javascript. I'm trying to evaluate the difference between a unix time string that is provided (presumably EST) and the current time in javascript format (any timezone the server is running in) and get the difference in hours/minutes/milliseconds.
I believe there are three approaches that I can try / have tried:
Convert the current server's javascript time in the given timezone to unix time, then subtract the provided unix time from it
Convert the provided unix time to javascript format based on the server's timezone and then subtract it from the server's current time
Convert both times to UTC or GMT and do math on it
I have scoured StackOverflow and tried many different approaches for these approaches and have not been able to get an accurate value.
For example, if the provided unix time is 1599206400000, and the current server's javascript time is Fri Sep 04 2020 16:47:26 GMT-0500 (Central Daylight Time), how do I get the difference in milliseconds between the two?
I apologize that there is no code example. The reason for this is I have tried so many different revisions of code without success, what I have in front of me doesn't reflect all of those efforts any longer.
Please help if you can and thank you in advance! I've been struggling with this problem for two days straight!
Server: Recommend to use UTC (ISO-8601 format). It is the standard serialization format.
Client: Client can process times locally and send UTC equiv. using toISOString to Server.
If you are looking for plain JS code, getTime() - this returns Unix time and is timezone-free.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
Lets take your example:
const timeA = 1599206400000; // already Unix time
const timeB = new Date(2020, 08, 04, 16, 47, 26, 531).getTime(); // getTime()
console.log(timeA, timeB, difference(timeB - timeA));
Output:
1599206400000 1599218246531 {hour: 3, min: 17, seconds: 26, milliseconds: 531}
Definition of difference function:
const difference = (millis) => {
const parts = [(millis / 3600000) % 60, (millis / 60000) % 60, (millis / 1000) % 60, millis % 1000];
const [hour, min, seconds, milliseconds] = parts.map((v) => parseInt(v));
return { hour, min, seconds, milliseconds };
};
// timestamp
var d = new Date()
d.setHours(4) // 4am
d.setMinutes(00) //00 minutes
var unixTimeStamp = Math.floor(d.getTime() / 1000); // converts to unix time
console.log(unixTimeStamp)
var apicurrentTime
var timeStamp
var differenceintime = apicurrentTime - timeStamp
I. You could use the momentjs to solve this problem:
timestampInMilliseconds = 1599206400000;
currentTimestampInMilliseconds = parseInt(moment.utc().format('x'));
currentTimestampInMilliseconds - timestampInMilliseconds;
// Example return value 94092301
To get the current time in UTC use: moment.utc()
To get the timestamp from a momentJS date formatted in milliseconds use: format('x')
You also need to cast it to int (with help of parseInt function) directly cause the output of format function is of type string
II. The plain JS solution is even simpler:
timestampInMilliseconds = 1599206400000;
currentTimestampInMilliseconds = (new Date).getTime();
currentTimestampInMilliseconds - timestampInMilliseconds;
// Example return value 94092301
You can freely use getTime() in this case, cause the official docs say: getTime() always uses UTC for time representation

How to convert dates with 3 letter timezone abbreviation, to UTC, in Javascript?

I need to convert datetimes from an input format which I can't change (this: "Tue, 30 Jul 2019 21:15:53 GMT") to UTC, in Javascript.
I actually need to get these dates as the number of milliseconds since the Unix epoch (1970) but getting in UTC would be a start.
Is there a way to do this easily? I can use a 3rd party library if needed. I've heard of moment-timezone.js but not clear how to parse the 3 letter timezone, i.e. these: https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations.
The correct solution is a library that maps these abbreviations to offsets from GMT. Neither moment-timezone, nor date-fns-tz, nor luxon, nor timezone-support do this, but timezone-abbr-offsets does and is very minimalistic.
Fortunately, new Date() can parse your format minus the timezone, so we'll split that away and calculate the offset back:
import timezones from 'timezone-abbr-offsets';
function abbrTzToUtc(dateString) {
// Get the date and the timezone from the input string
let [, date, tz] = dateString.match(/^(.*)\s+(\w+)$/);
// Ignore the timezone and parse the date as GMT
date = new Date(date + 'Z');
// Add the offset caused by the original timezone
date = new Date(date.getTime() + timezones[tz] * 60 * 1000);
return date;
}
console.log(abbrTzToUtc('Tue, 30 Jul 2019 21:15:53 MET'));
As a test, the code above should return 2019-07-30T22:15:53.000Z.
If you want number of milliseconds since the Unix epoch, return date.getTime() instead.
If you want to convert the date into UTC format you can use toISOString()
new Date('Tue, 30 Jul 2019 21:15:53 GMT').toISOString()
For more info please check this reference
Moreover, to convert the date into milliseconds you can use Date.UTC()
Date.UTC(year[, month[, day[, hour[, minute[, second[, millisecond]]]]]])
reference
Example:
utcMillisecond = (e) => {
const regex = /(T)|(:)|(-)/g;
const utc = new Date(e).toISOString().slice(0, 19).replace(regex, ' ').split(' ');
const utcMillisecond = Date.UTC(utc[0], utc[1], utc[2], utc[3], utc[4])
return utcMillisecond
}
utcMillisecond("Tue, 30 Jul 2019 21:15:53 GMT")
//1567199700000

postgresql to_timestamp returns different date than represented by the timestamp

Here's a replication of the problem:
I get the timestamp of now via JavaScript as
var ts = +new Date // 1368971991090
console.log( new Date(1368971991090) ); // Sun May 19 2013 13:59:51 GMT+0000 (GMT)
Then in my Postgres console,
# select to_timestamp(1368971991090);
to_timestamp
--------------------------------
45350-12-30 05:31:29.999872+00
(1 row)
A date way too much into the future.The docs of JavaScript Date#getTime say it returns milliseconds starting from the epoch; same as the argument type Postgres' to_timestamp accepts. Java's Date#getTime returns same value as JS Date#getTime.
Quote from postgresql doc from your link:
it accepts a double precision argument and converts from Unix epoch
(seconds since 1970-01-01 00:00:00+00) to timestamp with time zone.
Key -
seconds since
And in JS doc:
number of milliseconds since 1 January 1970 00:00:00 UTC
Don't know if this helps anyone, but I ran into the same issue recently. The solution was to convert the JS timestamp to seconds since the epoch, instead of milliseconds.
const millisecondsSinceEpoch = Date.now();
// output: 1631828038018
const secondsSinceEpoch = Math.round(Date.now() / 1000);
// output: 1631829225
In Postgres:
SELECT to_timestamp(1631828038018);
// output: 53680-07-27 14:06:57.999872
SELECT to_timestamp(1631829225);
// output: 2021-09-16 22:53:45+01

Categories

Resources