toIso8601StringWithOffset method

String toIso8601StringWithOffset()

Converts this DateTime to an ISO 8601 string with timezone offset.

This method extends the standard toIso8601String() by appending the timezone offset. For UTC dates, the offset string is empty, resulting in a standard ISO 8601 UTC format. For local dates, the offset is appended in the ±HH:MM format.

Returns: An ISO 8601 formatted string with timezone offset (e.g., "2024-08-07T12:34:56.789+07:00" or "2024-08-07T12:34:56.789" for UTC).

Example:

final localTime = DateTime.now();
print(localTime.toIso8601StringWithOffset());
// "2024-08-07T12:34:56.789+07:00"

final utcTime = DateTime.now().toUtc();
print(utcTime.toIso8601StringWithOffset());
// "2024-08-07T12:34:56.789" (no offset for UTC)

Implementation

String toIso8601StringWithOffset() {
  String iso8601String = toIso8601String();
  String offsetString = getTimezoneOffsetString();
  return iso8601String + offsetString;
}