Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Instant as valid fetch Property #1019

Open
Ditscheridou opened this issue Nov 1, 2021 · 3 comments
Open

Implement Instant as valid fetch Property #1019

Ditscheridou opened this issue Nov 1, 2021 · 3 comments
Labels
enhancement New feature or request

Comments

@Ditscheridou
Copy link

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

@Ditscheridou Ditscheridou added the enhancement New feature or request label Nov 1, 2021
@greenrobot-team
Copy link
Member

greenrobot-team commented Nov 2, 2021

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

@Ditscheridou
Copy link
Author

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

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

@greenrobot-team
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants