Skip to content

Date saved incorrectly with java.time codecs enabled #4390

Closed
@csmager

Description

@csmager

I ran into this when I enabled java.time codecs on our Spring web application, as I'd like to save LocalDate as UTC rather than with the system default timezone.

I couldn't log into the app, and I chased this down to the MongoIndexedSessionRepository saving my session with an expiry date of midnight UTC this morning. This effectively meant there was no session, as they were created as expired.

I've now managed to get this down to a repro. It seems because there is a 'convertible pair' of Date and LocalDate, the conversion decides that it should convert Date to LocalDate, which is a lossy conversion.

I've tested with Spring Boot 2.7.12. My config looks like this:

@Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {

    @Override
    protected String getDatabaseName() {
        return "test";
    }

    @Override
    public MongoClient mongoClient() {
        return MongoClients.create("mongodb://localhost:27017/test");
    }

    @Override
    public MongoCustomConversions customConversions() {
        return MongoCustomConversions.create(
            MongoConverterConfigurationAdapter::useNativeDriverJavaTimeCodecs);
    }
}

And a simple test:

@SpringBootTest
public class DateTests {

    @Autowired
    private MongoOperations mongoOperations;

    @Test
    public void write_and_read_date() {
        var date = Date.from(Instant.now());

        var obj = new BasicDBObject("date", date);

        this.mongoOperations.save(obj, "test");

        var id = obj.get("_id");

        var result = this.mongoOperations.findById(id, BasicDBObject.class, "test");

        var resultDate = result.get("date");

        assertThat(resultDate).isEqualTo(date);
    }
}

That fails like this:

Expected: 2023-05-18T17:01:46.197 (java.util.Date)
Actual: 2023-05-18T01:00:00.000 (java.util.Date)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions