How to get data from **Realm database** using **date object**?

依然范特西╮ 提交于 2019-12-01 11:44:56

问题


I have tried some realm queries but not getting that result which I want

let's consider below table for example(Realm table):

id    Name  DateTimeStamp

1      A    2017-01-01 08:00:00
2      B    2017-01-01 15:00:00
3      C    2017-01-02 08:00:00

Now I want all those records which match the date "2017-01-01".so for this case I should get 2 records from realm table.Right now I am not getting any record.

For information "DateTimeStamp" column datatype is "Date".and yes I need to store date and time both in the database as you can see on the table.

Query i have tried is:

 long cnt = realm.where(ReservationObject.class).equalTo("DateTimeStamp",dateObject).count();

Please help me with this... Thanks in advance...


回答1:


You need to set up Date objects for 2017-01-01 00:00:00 and 2017-01-02 00:00:00 and query inbetween.

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, 1); // make sure month stays valid
calendar.set(Calendar.YEAR, 2017);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date jan1 = new Date(calendar.getTimeInMillis());
calendar.set(Calendar.DAY_OF_MONTH, 2);
Date jan2 = new Date(calendar.getTimeInMillis());

Then

realm.where(ReservationObject.class)
     .greaterThanOrEqualTo("DateTimeStamp", jan1)
     .lessThan("DateTimeStamp", jan2)
     .findAll()



回答2:


Use contains it work like LIKE

long cnt =
 realm.where(ReservationObject.class)
 .contains("DateTimeStamp",dateObject).count();

OR Latest version have

public RealmQuery<E> like(String fieldName,
                      String value,
                      Case casing)


来源:https://stackoverflow.com/questions/48205164/how-to-get-data-from-realm-database-using-date-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!