Sunrise and sunset time

607 Views Asked by At

Hi i need help with my weather api in Javascript with Openweathermap API. I want it to display the time for the sunrise and the sunset of the searched city. Currently its just showing the unix time like for example: 1686799061. I want it to say the time in like 05:43 or something else. I hope yall can help me. My code strips for the sunrise and sunset are the following:

How to fetch the time:

const { sunrise } = data.sys;
const { sunset } = data.sys;

showing:

document.querySelector(".sunrise").innerText = "Sonnenaufgang: " + sunrise;
document.querySelector(".sunset").innerText = "Sonnenuntergang: " + sunset;

I rly hope someone can help me with that!!!

I tried to do it with the .format('HH:mm a') which just causes my weather api to crash and not showing anything. I really need help with that one.

1

There are 1 best solutions below

3
Andy On

Intl.DateTimeFormat allows you create a date/time per locale in a format of your choosing.

// Mock data
const data = { sys: { sunrise: 1686819713693 } };

// Grab the sunrise timestamp
const { sunrise } = data.sys;

// Set the locale
const locale = 'en-GB';

function getFormattedTime(timestamp, locale) {
  
  // Create a date from the timestamp
  const date = new Date(timestamp);

  // Restrict the formatting to hour & minute
  const options = { hour: 'numeric', minute: 'numeric' };

  // Return appropriately formatted time
  return new Intl.DateTimeFormat(locale, options).format(date);

}

// Select the element
const sunriseEl = document.querySelector('.sunrise');

// Using a template string add the sunrise variable as
// text content to the element
sunriseEl.textContent = `Sonnenaufgang: ${getFormattedTime(sunrise, locale)}`;
<p class="sunrise"></p>