Support for ZonedDateTime with MongoDB using Codec for Java

Can there be native support to ZonedDateTime in MongoDB java Driver sync. Seems it only have LocalDateTime implemented as part of JSR310
Supported classes are The high level API contains the following key classes:

  1. LocalDate - A date, with no time nor zone-offset
  2. LocalTime - A time, with no date nor zone-offset
  3. LocalDateTime - A date-time, with no zone-offset
  4. OffsetTime - A time and zone-offset, with no date
  5. OffsetDateTime - A date-time and zone-offset
  6. ZonedDateTime - A date-time, zone-offset and time-zone
  7. ZoneOffset - An offset from the time in UTC/GMT
  8. ZoneId - A time-zone identifier, used to find the underlying rules

Thanks for letting us know about your feature request for native support of ZonedDateTime.

While we don’t have this on our roadmap currently, I’ve added it to the JAVA project so that we can gauge popularity and interest. Feel free to upvote it here, and to add any additional information about your specific use case.

1 Like

Fatal error : Uncaught MongoDB\Driver\Exception\ConnectionTimeoutException: No suitable servers found (serverSelectionTryOnce set): [Failed to receive length header from server. calling hello on ‘cluster0-shard-00-02.sw31d.mongodb.net:27017’] [Failed to receive length header from server. calling hello on ‘cluster0-shard-00-00.sw31d.mongodb.net:27017’] [Failed to receive length header from server. calling hello on ‘cluster0-shard-00-01.sw31d.mongodb.net:27017’] in C:\xampp\htdocs\php_mongdb\vendor\mongodb\mongodb\src\functions.php:520 Stack trace: #0 C:\xampp\htdocs\php_mongdb\vendor\mongodb\mongodb\src\functions.php(520): MongoDB\Driver\Manager->selectServer(Object(MongoDB\Driver\ReadPreference)) #1 C:\xampp\htdocs\php_mongdb\vendor\mongodb\mongodb\src\Collection.php(932): MongoDB\select_server(Object(MongoDB\Driver\Manager), Array) #2 C:\xampp\htdocs\php_mongdb\index.php(14): MongoDB\Collection->insertOne(Array) #3 {main} thrown in C:\xampp\htdocs\php_mongdb\vendor\mongodb\mongodb\src\functions.php on line 520

how can i fix this

I am doing the following in java please confirm if i am on the right path
This is based on implementation of mongodb jsr310

DateTimeBasedCodec

abstract class DateTimeBasedCodec<T> implements Codec<T> {

    long validateAndReadDateTime(final BsonReader reader) {
        BsonType currentType = reader.getCurrentBsonType();
        if (!currentType.equals(BsonType.DATE_TIME)) {
            throw new CodecConfigurationException(format("Could not decode into %s, expected '%s' BsonType but got '%s'.",
                    getEncoderClass().getSimpleName(), BsonType.DATE_TIME, currentType));
        }
        return reader.readDateTime();
    }

}

ZonedDateTimeCodec

public class ZonedDateTimeCodec extends DateTimeBasedCodec<ZonedDateTime> {

    @Override
    public ZonedDateTime decode(final BsonReader reader, final DecoderContext decoderContext) {
        return Instant.ofEpochMilli(validateAndReadDateTime(reader)).atZone(ZoneOffset.UTC);
    }

    @Override
    public void encode(final BsonWriter writer, final ZonedDateTime value, final EncoderContext encoderContext) {
        try {
            writer.writeDateTime(value.toInstant().toEpochMilli());
        } catch (ArithmeticException e) {
            throw new CodecConfigurationException(format("Unsupported ZonedDateTime value '%s' could not be converted to milliseconds: %s",
                    value, e.getMessage()), e);
        }
    }

    @Override
    public Class<ZonedDateTime> getEncoderClass() {
        return ZonedDateTime.class;
    }
}

Jsr310CodecProvider.java

public class Jsr310CodecProvider implements CodecProvider {
    private static final Map<Class<?>, Codec<?>> JSR310_CODEC_MAP = new HashMap<>();

    static {
        try {
            putCodec(new ZonedDateTimeCodec());
        } catch (ClassNotFoundException classNotFoundException) {
            // empty catch block
        }
    }

    private static void putCodec(Codec<?> codec) {
        JSR310_CODEC_MAP.put(codec.getEncoderClass(), codec);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
        return (Codec<T>) JSR310_CODEC_MAP.get(clazz);
    }

    @Override
    public String toString() {
        return "Jsr310CodecProvider{}";
    }
}

These are very common use case, Do we have official document around how to add custom codec for java type to bson?