vvo / tzdb

🕰 Simplified, grouped and always up to date list of time zones, with major cities
MIT License
772 stars 53 forks source link

Documentation FR: Actual usage in a front-end select component #283

Open timfee opened 1 year ago

timfee commented 1 year ago

I ended up writing this wrapper to present a nice dropdown list:

// util/timezones.ts
import { rawTimeZones } from "@vvo/tzdb"

export type TimeZoneData = {
  /**
   * A map of display strings to time zone data. The key is a formatted string
   * that represents the time zone offset and alternative name (e.g.,
   * "(GMT+02:00) Central European Time"), and the value is an object containing
   * the IANA time zone name (e.g., "Europe/Berlin") and an array of associated
   * group names.
   */
  timeZoneMap: Map<string, { value: string; group: string[] }>
  /**
   * A map of group names to IANA time zone names. The key is the group name
   * (e.g., "US/Central"), and the value is the corresponding IANA time zone
   * name (e.g., "America/Chicago").
   */
  groupLookupMap: Map<string, string>
}
/**
 * Generates a manageable amount of of display strings (<200) in
 * {@link timeZoneMap}, as well as a {@link groupLookupMap} so we can
 * process any timezone to its corresponding value in the UI.
 */
function getTimezoneData(): TimeZoneData {
  const timeZoneMap = new Map<string, { value: string; group: string[] }>()
  const groupLookupMap = new Map<string, string>()

  // Iterate through the rawTimeZones array
  for (const { rawFormat, name, group } of rawTimeZones) {
    // Add the display string to timeZoneMap if it doesn't exist
    if (!timeZoneMap.has(rawFormat)) {
      timeZoneMap.set(rawFormat, {
        value: name,
        group,
      })
    }

    // Add the time zone name to groupLookupMap for each group in rawTimeZone.group
    for (const tz of group) {
      if (!groupLookupMap.has(tz)) {
        groupLookupMap.set(tz, name)
      }
    }
  }

  return { timeZoneMap, groupLookupMap }
}

export default getTimezoneData

And created a React component that shows a dropdown:

// components/TimeZonePicker.tsx
const { groupLookupMap, timeZoneMap } = getTimezoneData()

export default function TimezonePicker() {
  const {
    state: { timeZone },
    dispatch,
  } = useProvider()

  // ⭐️ The relevant bit here; how to handle a TZ (e.g. Intl.DateTimeFormat().resolvedOptions)
  // that may not have been chosen as the value for that specific locale.
  //
  const selectedTimeZoneValue = groupLookupMap.get(timeZone)

  return (
    <div className="flex-grow">
      <label
        htmlFor="location"
        className="block text-sm font-medium leading-0 text-gray-900">
        Timezone
      </label>

      <select
        value={selectedTimeZoneValue}
        id="location"
        name="location"
        className="mt-1 block w-full rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-accent-600 sm:text-sm sm:leading-6"
        onChange={(e) => {
          dispatch({
            type: "SET_TIMEZONE",
            payload: e.currentTarget.value,
          })
        }}>
        {[...timeZoneMap].map(([display, { value }]) => (
          <option key={display} value={value}>
            {`GMT${display}`}
          </option>
        ))}
      </select>
    </div>
  )
}

When I set up my state (or in my case reducer), I pass it

  const timeZone =
    values.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? "UTC"

Not sure if this approach might be helpful to include in the docs, but figured I'd at least immortalize it here since it's something that I've been working on :)

Screen Shot 2023-03-22 at 12 16 52 2

Thanks for the library, @vvo 👏🏼