public static function formatDate($timestamp, $type = 'full_sort', $format = '', $timezone = null) {
    // Determine the format to use.
    switch ($type) {
      case 'date_sort':
        $format = 'Y-m-d';
        break;
      case 'date_long':
        $format = 'l, F j, Y';
        break;
      case 'date_med':
        $format = 'j M Y';
        break;
      case 'date_short':
        $format = 'n/d/Y';
        break;
      case 'time_sort':
        $format = 'H:i T';
        break;
      case 'time_long':
        $format = 'g:i:s A T';
        break;
      case 'time_med':
        $format = 'g:i:s A';
        break;
      case 'time_short':
        $format = 'g:i A';
        break;
      case 'full_sort':
        $format = 'Y-m-d H:i T';
        break;
      case 'full_long':
        $format = 'l, F j, Y g:i A T';
        break;
      case 'full_med':
        $format = 'j M Y g:i A T';
        break;
      case 'full_short':
        $format = 'n/d/Y g:i A T';
        break;
      case 'custom':
      default:
        break;
    }
    // Create a date object from the timestamp.
    try {
      $date = new \DateTime(gmdate('c', (int) $timestamp));
      if (isset($timezone)) {
        if (!is_object($timezone)) {
          $timezone = new \DateTimeZone($timezone);
        }
        $date->setTimezone($timezone);
      } else {
        $date->setTimezone(new \DateTimeZone(date_default_timezone_get()));
      }
    } catch (\Exception $e) {
      throw new \Exception("Error formatting date: $e");
    }
    return $date->format($format);
  }