Tuesday, January 20, 2009

Converting Salesforce API DateTime from UTC to the users timezone using TimeZoneSidKey

With .NET 3.5 the System.TimeZoneInfo class can be used to convert the UTC DateTime to the users time zone, including changes required for daylight savings. The basic steps involve:
  GetUserInfoResult userInfo = binding.getUserInfo();
  string userTimeZoneSidKey = userInfo.userTimeZone;

  string timeZoneKey = string.Empty;
  switch (userTimeZoneSidKey)
  {
    case "America/Los_Angeles":
      timeZoneKey = "Pacific Standard Time";
      break;
    case "Pacific/Auckland":
      timeZoneKey = "New Zealand Standard Time";
      break;
    //...
  }

  TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneKey);
  DateTime timeZoneDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, 
     timeZone);
The pain point here is the huge switch statement required to map the Salesforce TimeZoneSidKey to a valid TimeZoneInfo Id. See also: