CodingNic

Weather API & Current Conditions

Format the Location’s Local Time

Weather API & Current Conditions 20 min read

Format the Location’s Local Time

Format the Location’s Local Time

Task

Make the date/time on the card reflect the searched location instead of the learner’s computer timezone.

Open

Add this helper before displayCurrent() and keep the existing call from the renderer.

Implementation

javascript
function formatDate(timestamp, timezone) {
  return new Intl.DateTimeFormat("en-US", {
    weekday: "short",
    day: "2-digit",
    month: "short",
    hour: "2-digit",
    minute: "2-digit",
    hour12: true,
    timeZone: "UTC"
  }).format(new Date((timestamp + timezone) * 1000));
}

OpenWeatherMap supplies a UTC timestamp and a timezone offset in seconds. The helper adds the offset and then formats the result in UTC so the browser does not apply its own local timezone again.

Test

Search for a city in a timezone different from yours and compare the displayed time with the location’s expected local time.

Expected result

The current card now shows a location-aware timestamp.

Checkpoint

Before moving on, confirm the expected result in the running app and make sure the browser console has no blocking errors.