convertTimezoneWithString static method

String convertTimezoneWithString(
  1. String fromTime,
  2. TGTimeZone fromTimeZone,
  3. TGTimeZone toTimeZone, {
  4. String dateTimePattern = _DATE_TIME_PATTERN,
})

Implementation

static String convertTimezoneWithString(
    String fromTime, TGTimeZone fromTimeZone, TGTimeZone toTimeZone,
    {String dateTimePattern = _DATE_TIME_PATTERN}) {
  final DateFormat dateFormat = DateFormat(dateTimePattern);

  // Parse the input datetime
  final originalTime = DateTime.parse(fromTime);

  // Get the offset for the source and target timezones
  Duration? fromOffset = _getTimeZoneOffsets(fromTimeZone);
  Duration? toOffset = _getTimeZoneOffsets(toTimeZone);

  if (!toOffset.isNegative && fromOffset.isNegative) {
    fromOffset = fromOffset + const Duration(hours: 1);
  }

  if (toOffset.isNegative && !fromOffset.isNegative) {
    fromOffset = fromOffset - const Duration(hours: 1);
  }

  // Adjust the time fromTimezone > toTimezone
  final convertedTime = originalTime.subtract(fromOffset - toOffset);
  return dateFormat.format(convertedTime);
}