encodeDateTime method

String encodeDateTime(
  1. DateTime? datetime, {
  2. bool isDateOnly = false,
})

Implementation

String encodeDateTime(DateTime? datetime, {bool isDateOnly = false}) {
    if (datetime == null)
    return 'null';

  var string = datetime.toIso8601String();

  if (isDateOnly) {
    string = string.split("T").first;
  } else {

    // ISO8601 UTC times already carry Z, but local times carry no timezone info
    // so this code will append it.
    if (!datetime.isUtc) {
      var timezoneHourOffset = datetime.timeZoneOffset.inHours;
      var timezoneMinuteOffset = datetime.timeZoneOffset.inMinutes % 60;

      // Note that the sign is stripped via abs() and appended later.
      var hourComponent = timezoneHourOffset.abs().toString().padLeft(2, "0");
      var minuteComponent = timezoneMinuteOffset.abs().toString().padLeft(2, "0");

      if (timezoneHourOffset >= 0) {
        hourComponent = "+${hourComponent}";
      } else {
        hourComponent = "-${hourComponent}";
      }

      var timezoneString = [hourComponent, minuteComponent].join(":");
      string = [string, timezoneString].join("");
    }
  }

  if (string.substring(0, 1) == "-") {
    // Postgresql uses a BC suffix for dates rather than the negative prefix returned by
    // dart's ISO8601 date string.
    string = string.substring(1) + " BC";
  } else if (string.substring(0, 1) == "+") {
    // Postgresql doesn't allow leading + signs for 6 digit dates. Strip it out.
    string = string.substring(1);
  }

  return "'${string}'";
}