Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 442
Lokesh Desai Avatar asked Jun 18 '26 02:06

Lokesh Desai


1 Answers

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()
like image 84
EpicPandaForce Avatar answered Jun 23 '26 22:06

EpicPandaForce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!