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,

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 😀


Well, there are some things to consider here.

  • Do you want to take time zones into account? How many days there are in between two dates, depends on the time zone where you are in. For example,

    2021-01-31T23:00:00Z      until 2021-02-03T11:00:00Z      is 4 days inclusive
    2021-02-01T01:00:00+02:00 until 2021-02-03T13:00:00+02:00 is 3 days inclusive

    Both start times have the same timestamp. The same counts for the end times.

  • What is a month? Again, this depends on whether you want to take time zones into account. And you must know the exact date the timestamp represents in order to calculate the number of months in between, because the length of a month depends on, well, the month and even the year.

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);

Answered By – MC Emperor

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published