25 - Interactive Time Zone Converter

Description

Create a React component that displays the current time in multiple global cities based on user input or selection.

  • Provide a way for users to choose a reference time zone (e.g., by selecting a city or entering a time zone name).

  • Display the current time in the reference time zone.

  • Offer a list of other cities or time zones with their corresponding current times, updated dynamically.

  • Optionally, allow users to save favorite time zones for quick access.

Algorithm

  1. Create a React component with state to manage the reference time zone, displayed cities, and potentially saved favorites.

  2. Fetch a list of time zones and their corresponding cities from a data source (e.g., a local list or external API).

  3. Implement functions to:

    • Handle user input or selection of the reference time zone.

    • Calculate the current time in different time zones based on the reference.

    • Update the displayed times accordingly.

  4. Manage saved favorites (if applicable) using local storage or a database.

  5. Render the UI elements for time zone selection, current time display, and city list.

Code

import React, { useState, useEffect } from 'react';

const TimeZoneConverter = () => {
  const [referenceTimeZone, setReferenceTimeZone] = useState('America/Los_Angeles');
  const [selectedCities, setSelectedCities] = useState([]);

  useEffect(() => {
    // Fetch time zone data (replace with your preferred data source)
    fetch('https://worldtimeapi.org/api/timezone')
      .then((response) => response.json())
      .then((data) => setSelectedCities(data.timezones));
  }, []);

  const handleReferenceTimeZoneChange = (e) => {
    setReferenceTimeZone(e.target.value);
  };

  const getCurrentTimeInZone = (zone) => {
    const now = new Date();
    const offset = now.getTimezoneOffset() * 60 * 1000; // Offset in milliseconds
    const zonedTime = new Date(now.getTime() - offset + zone.offset * 60 * 1000);
    return zonedTime.toLocaleTimeString();
  };

  return (
    <div className="time-zone-converter">
      <h1>Time Zone Converter</h1>
      <select value={referenceTimeZone} onChange={handleReferenceTimeZoneChange}>
        {selectedCities.map((city) => (
          <option key={city.zone} value={city.zone}>
            {city.zoneName} ({city.countryName})
          </option>
        ))}
      </select>
      <p>Current time in {referenceTimeZone}: {getCurrentTimeInZone(selectedCities.find((city) => city.zone === referenceTimeZone))}</p>
      <ul>
        {selectedCities.map((city) => (
          <li key={city.zone}>
            {city.zoneName} ({city.countryName}): {getCurrentTimeInZone(city)}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default TimeZoneConverter;

Explanation

  1. State Management: The component uses useState to manage the referenceTimeZone and selectedCities.

  2. Data Fetching: The useEffect hook fetches a list of time zones from an external API (replace with your preferred data source).

  3. Time Calculation: The getCurrentTimeInZone function calculates the current time in a given time zone using JavaScript's Date object and offset logic.

  4. UI Rendering: The component renders a select element for choosing the reference time zone, displays the current time in the reference zone, and lists other cities with their corresponding times.

Additional Notes

The basic application can be enhanced with:

  • Styling: Add CSS for visual appeal and user-friendly interactions.

  • Search: Implement a search bar to filter cities quickly.

  • Favorites: Allow users to save and manage favorite time zones.

  • Map Integration: Visualize time zones on a map for a more interactive experience.

Last updated