skip to Main Content

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


  1. You need to call toLocaleString directly on the date object not the rfc2822 string. I recommend implementing it like this

      let epochtime = weatherData.dt;
      let timezone = weatherData.timezone;
      const UNIXDate = new Date((epochtime + timezone) * 1000);
    
      const options = {
        weekday: "long",
        month: "long",
        day: "numeric",
        hour: "numeric",
        minute: "numeric",
        hour12: true
      };
    
    const longFormatDateTime =  UNIXDate.toLocaleString("en-us",options);
    

    Hope this helps.

    Login or Signup to reply.
  2. 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.

    function formatUnixTime(epochTime, utcOffsetSeconds, options = {}) {
      const date = new Date((epochTime + utcOffsetSeconds) * 1000);
      return date.toLocaleTimeString([], { timeZone: 'UTC', ...options });
    }
    
    function getLongFormatUnixTime(epochTime, utcOffsetSeconds) {
      const options = { weekday: 'long', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', hour12: true };
      return formatUnixTime(epochTime, utcOffsetSeconds, options);
    }
    
    const weatherData = { 
      dt: 1679888142,
      timezone: 7200
    }
     
    const epochTime = weatherData.dt;
    const utcOffset = weatherData.timezone;
     
    console.log('Unix time:     ', epochTime);
    console.log('UTC Offset (s):', utcOffset);
    console.log('Time (UTC):    ', getLongFormatUnixTime(epochTime, 0));
    console.log('Time (in zone):', getLongFormatUnixTime(epochTime, utcOffset));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search