Detecting a users Country with Timezone

I recently stumbled across a stack overflow comment when doing some geolocation research that lead me to this bit of JavaScript.

Intl.DateTimeFormat().resolvedOptions().timeZone

It seems like a low stakes (and probably low reliability) way to detect a users country without any 3rd party, api, or permission request. Browser support is pretty good too. The stack overflow link above contains a really detailed codepen to detect many countries, but let’s keep it simple and just try to detect one.

Let’s use my country of Canada as an example. Create an array of timezones from the tz database and check the users timezone to see if it’s contained in the array.

Here’s a really quick and dirty test:

<p>Are you in Canada?: <span id="country">Unknown</span></p>

  <script>
    let tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
    let canadianTzs = [
      "America/Cambridge_Bay",
      "America/Dawson",
      "America/Dawson_Creek",
      "America/Edmonton",
      "America/Fort_Nelson",
      "America/Glace_Bay",
      "America/Goose_Bay",
      "America/Halifax",
      "America/Yellowknife",
      "Canada/Mountain",
      "Canada/Atlantic",
      "America/Inuvik",
      "America/Iqaluit",
      "America/Moncton",
      "America/Rankin_Inlet",
      "America/Regina",
      "Canada/Saskatchewan",
      "America/Resolute",
      "America/St_Johns",
      "Canada/Newfoundland",
      "America/Swift_Current",
      "America/Toronto",
      "America/Montreal",
      "America/Nassau",
      "America/Nipigon",
      "America/Thunder_Bay",
      "Canada/Eastern",
      "America/Vancouver",
      "Canada/Pacific",
      "America/Whitehorse",
      "Canada/Yukon",
      "America/Winnipeg",
      "America/Rainy_River",
      "Canada/Central",
    ];
    if (tz) {
      let tzspan = document.querySelector("#country");
      if (tzspan) {
        let answer = "Unknown";
        if (canadianTzs.includes(tz)) {
          answer = "Yes";
        } else {
          answer = "No";
        }
        tzspan.textContent = answer;
      }
    }
  </script>

The result:

Are you in Canada?: Unknown

Here’s the codepen from that inspiration stack overflow post that has a much more comprehensive country detector: