Converting timezones from the Xero API to Windows format (.Net)

Converting timezones from the Xero API to Windows format (.Net)

Hi everybody. Was working on a Xero integration today and was reminded of a little gotcha when integrating data using the Xero API - timezone formatting.

You see, Xero maintains its own list of keys to indicate timezones, but these aren’t much use to use .Net developers because they don’t match the built-in identifiers in the TimeZoneInfo class.

At first glance it seems like you may need to manually write a mapping, but look a little closer - each identifier in the Xero list is actually a stripped-down version of our Windows equivalents. Specifically, Xero has simply stripped the non-alpha characters like spaces and full-stops and then capitalized it.

So, here’s a handy little utility we use to do the conversion. This allows us to sync invoices from Xero but store the due date etc in UTC, so our integrations can continue working with it safely.

/// <summary>
/// Xero provides timezones as per https://github.com/XeroAPI/XeroAPI-Schemas/blob/master/src/main/resources/XeroSchemas/v2.00/Timezone.xsd
/// I have found that their key is just a capitalized and non-char-stripped version of the Windows TimeZone IDs. This function
/// will convert eg. NEWZEALANDSTANDARDTIME to "New Zealand Standard Time" or "WCENTRALAFRICASTANDARDTIME" to "W. Central Africa Standard Time"
/// Refer https://support.microsoft.com/en-us/help/973627/microsoft-time-zone-index-values for the Windows mappings
/// </summary>
/// <param name="xeroTimeZone"></param>
/// <returns></returns>
protected virtual string GetWindowsTZFromXeroTZ(string xeroTimeZone)
{
  // Known exceptions
  // UTC+12, UTC02, RUSSIATIMEZONE11
  var rx = new System.Text.RegularExpressions.Regex("[^a-zA-Z]");
  foreach (var tz in TimeZoneInfo.GetSystemTimeZones()) {
    var key = rx.Replace(tz.Id, "").ToUpper();
    if (xeroTimeZone == key) return tz.Id;
  }

  throw new DeveloperException($@"We could not cross reference Xero time zone '{xeroTimeZone}' with a known Windows timezone");
}

Easy huh? Hope you find it useful.

Introducing SyncHub

Introducing SyncHub

The Dilemma of Being a Non-Technical Founder in an All Tech World

The Dilemma of Being a Non-Technical Founder in an All Tech World