decodeDateTime method

DateTime decodeDateTime(
  1. String value,
  2. int pgType, {
  3. String? connectionName,
})

Decodes value into a DateTime instance.

Note: it will convert it to local time (via DateTime.toLocal)

Implementation

DateTime decodeDateTime(String value, int pgType, {String? connectionName}) {
  // Built in Dart dates can either be local time or utc. Which means that the
  // the postgresql timezone parameter for the connection must be either set
  // to UTC, or the local time of the server on which the client is running.
  // This restriction could be relaxed by using a more advanced date library
  // capable of creating DateTimes for a non-local time zone.

  if (value == 'infinity' || value == '-infinity')
    throw _error('A timestamp value "$value", cannot be represented '
        'as a Dart object.', connectionName);
        //if infinity values are required, rewrite the sql query to cast
        //the value to a string, i.e. your_column::text.

  var formattedValue = value;

  // Postgresql uses a BC suffix rather than a negative prefix as in ISO8601.
  if (value.endsWith(' BC')) formattedValue = '-' + value.substring(0, value.length - 3);

  if (pgType == _TIMESTAMP) {
    formattedValue += 'Z';
  } else if (pgType == _TIMESTAMPZ) {
    // PG will return the timestamp in the connection's timezone. The resulting DateTime.parse will handle accordingly.
  } else if (pgType == _DATE) {
    formattedValue = formattedValue + 'T00:00:00Z';
  }

  return DateTime.parse(formattedValue).toLocal();
}