I obtained data from open weather API
dt:1679888142
timezone:7200
I’m trying to change UNIX time into local time by applying Date
object in JavaScript followed by toUTCString()
to get the local time.
The goal is to change the obtained local time 'Mon, 27 Mar 2023 05:35:42 GMT'
into long formatted time eg 'Monday, March 27 at 4:35 AM'
. when i apply the following code, its not formatting also adding my timezone difference to it
this is the following code
let epochtime = weatherData.dt;
let timezone = weatherData.timezone;
const rfc2822Date = new Date((epochtime + timezone) * 1000).toUTCString();
const options = {
weekday: "long",
month: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
hour12: true
};
const longFormatDateTime = rfc2822Date.toLocaleString("en-us",options);
i tried to pass the date once again into date object which will result in gmt+timezone and format. formatting seems to work but local time is wrong
2
Answers
You need to call
toLocaleString
directly on the date object not the rfc2822 string. I recommend implementing it like thisHope this helps.
Because we’re dealing with a fixed offset here, we can simply add the UTC offset in seconds to the epoch time when creating a Date object. We need to specify the ‘UTC’ timezone when formatting however, to avoid formatting in the client’s timezone.