objectbox-java icon indicating copy to clipboard operation
objectbox-java copied to clipboard

Implement Instant as valid fetch Property

Open Ditscheridou opened this issue 3 years ago • 3 comments

The "Date" property is outdated with Java 8 Time API, it would be nice to have Instant instead.

Ditscheridou avatar Nov 01 '21 10:11 Ditscheridou

Thanks! Note that for now you can add a converter class, e.g.

import java.time.Instant;
import java.util.Date;

/**
 * Converts an {@link Instant} to a {@link Date} to store in the database. Hence, if the instant represents a time too
 * far into the future or past that does not fit long milliseconds an exception is thrown.
 * <p>
 * Note that on some hardware this may lead to a loss in precision, e.g. if it supports microsecond or nanosecond time.
 * Use a custom {@link PropertyConverter} to store time with higher precision.
 */
public class InstantToDateConverter implements PropertyConverter<Instant, Date> {
    @Override
    public Instant convertToEntityProperty(Date databaseValue) {
        if (databaseValue == null) {
            return null;
        }
        return databaseValue.toInstant();
    }

    @Override
    public Date convertToDatabaseValue(Instant entityProperty) {
        if (entityProperty == null) {
            return null;
        }
        return new Date(entityProperty.toEpochMilli());
    }
}

and then on a property use

@Convert(dbType = Date.class, converter = InstantToDateConverter.class)
public Instant instant;

Related docs at https://docs.objectbox.io/advanced/custom-types

greenrobot-team avatar Nov 02 '21 07:11 greenrobot-team

yes, but i can`t use that for a Query like:

box<T>().query { equal(MyEntity_.fieldAsInstant,Instant.now()) }

Ditscheridou avatar Nov 02 '21 10:11 Ditscheridou

Use .toEpochMilli() for the query. Like Date the time is internally stored as a Long integer.

greenrobot-team avatar Nov 09 '21 14:11 greenrobot-team