javaandroid-studiodateandroid-calendarmilliseconds

Comparing two dates in millis to check if they are a certain time apart


I'm setting up an SQLite database on android studio that stores scheduled items, each containing a date variable as a long (date in millis).

I'm trying to create two functions that compare two dates in millis. The first function checks wether they are one week apart, the other function checks if they are one month apart (by the day, and not the exact time) so that:

weekApart(1621548000000, 1622073600000) = true, etc.

I'm doing this so that when when the user selects a date on the calendar, the current timestamp is recorded, and I can search the table for items which fall into the correct day or month.

Does anyone know how this could be done? Thank you for any answers.

Edit: Great answers, thank you all :D


Solution

  • Well, there are some things to consider here.

    If you don't care about time zones, you could just use

    long days = ChronoUnit.DAYS.between(Instant.ofEpochMillis(a), Instant.ofEpochMillis(b));
    

    Otherwise, you end up with something like

    ZoneId zoneId = ZoneId.of("Europe/Amsterdam");
    var start = Instant.ofEpochMilli(a).atZone(zoneId);
    var end = Instant.ofEpochMilli(a).atZone(zoneId);
    long days = ChronoUnit.DAYS.between(start, end);