0

I want to use Date type as Id in Room database, The main reason for this is to be able to check if this date is today. Any suggestion is appreciate

@Entity
data class DailyCount(@PrimaryKey
                  var date:DateTime,// JodaTime
                  var summ: MutableLiveData<Double>? = MutableLiveData())

I want to make query like this:

@Query("update DailyCount set summ = :sum where date = :dailyCount") //update if date is today
fun apdateCash(dailyCount: DateTime, sum: Double)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nurseyit Tursunkulov
  • 8,012
  • 12
  • 44
  • 78
  • I posted answer here, it is kind of duplicate https://stackoverflow.com/questions/56051963/how-to-use-joda-datetime-date-as-id-in-room-or-how-to-get-date-in-query – Nurseyit Tursunkulov May 09 '19 at 06:46
  • I posted answer here it is kind of duplicate https://stackoverflow.com/questions/56051963/how-to-use-joda-datetime-date-as-id-in-room-or-how-to-get-date-in-query – Nurseyit Tursunkulov May 09 '19 at 06:47

1 Answers1

1

Just use SimpleDateFormatter

String jsonDateStr = "03-09-2019 05:45:10"
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy");

try {
    return fmt.parse(jsonDateStr);
} catch(ParseException pe) {
    return //generate different unique ID like GUID random maybe;    
}

Now if you have a date object first, and you need to zero it out, you could do:

Date dateObject = Date("03-09-2019 05:45:10") //pseudo for visual
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy");

try {
     String dateWithZeroedTime = fmt.format(dateObject)
     return fmt.parse(dateWithZeroedTime) //"03-09-2019 00:00:00"   
} catch(ParseException pe) {
    return //generate different unique ID like GUID random maybe;    
}

Happy Coding!

Sam
  • 5,342
  • 1
  • 23
  • 39
  • fmt.format returns string. I need to get DateTime type for checking if this date is today – Nurseyit Tursunkulov May 08 '19 at 15:30
  • There are several great tools and wrappers to compare dates like the simple Calendar for example, but since I don't know your full use case, I updated the answer to convert back to the Date object with time zeroed out. – Sam May 08 '19 at 16:11
  • Updated with more details to help. – Sam May 08 '19 at 16:20