getUtcTimeFromLocal method

DateTime getUtcTimeFromLocal(
  1. double offset
)

Converts this local DateTime to UTC using the given timezone offset.

offset is the hours-ahead-of-UTC value for this DateTime's timezone. Positive for timezones east of UTC (e.g., 2.0 for UTC+2), negative for timezones west of UTC (e.g., -5.0 for UTC-5). Fractional values represent partial hours (e.g., 5.5 for UTC+5:30).

Always returns a non-null DateTime. Returns the original instance if offset is 0.

Example:

// 15:00 local in UTC+2 → 13:00 UTC
DateTime(2024, 6, 15, 15, 0).getUtcTimeFromLocal(2.0); // 13:00
// 10:00 local in UTC-5 → 15:00 UTC
DateTime(2024, 1, 15, 10, 0).getUtcTimeFromLocal(-5.0); // 15:00
// 10:30 local in UTC+5:30 → 05:00 UTC
DateTime(2024, 1, 15, 10, 30).getUtcTimeFromLocal(5.5); // 05:00

Implementation

DateTime getUtcTimeFromLocal(double offset) {
  if (offset == 0) {
    return this;
  }

  // Use truncate (not floor) so -5.5 → hours=-5, fraction=-0.5 (correct sign)
  final int hours = offset.truncate();
  final int minutes = ((offset - hours) * 60).round();

  // Subtract offset: UTC = local − offset
  return subtract(Duration(hours: hours, minutes: minutes));
}