1

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.

KaiSanjix
  • 11
  • 2
  • Does this answer your question? [Convert a Unix timestamp to time in JavaScript](https://stackoverflow.com/questions/847185/convert-a-unix-timestamp-to-time-in-javascript) – Lee Taylor Jun 15 '23 at 10:27

1 Answers1

0

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>
Andy
  • 61,948
  • 13
  • 68
  • 95
  • i typed it in but it says its not working. what is the variable or word that i need to paste into that code: document.querySelector(".sunrise").innerText = "Sonnenaufgang: " + sunrise; – KaiSanjix Jun 15 '23 at 10:12
  • @KaiSanjix I've added the some markup to the answer. I've used a [template string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) to add the formatted sunrise timestamp to the text content of the sunrise element. Hope it helps. – Andy Jun 15 '23 at 10:20
  • 1
    tysm it worked perfectly – KaiSanjix Jun 15 '23 at 10:40