Pepe
Pepe

Reputation: 59

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

Upvotes: 0

Views: 1595

Answers (2)

MC Emperor
MC Emperor

Reputation: 22997

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

Upvotes: 2

felipecrp
felipecrp

Reputation: 1069

You may find the difference in days between the two dates.

First, you can convert your long numbers to a calendar:

Calendar date1 = Calendar.getInstance();
date1.setTimeInMillis(1621548000000L);

Calendar date2 = Calendar.getInstance();
date2.setTimeInMillis(1622073600000L);

Next, you can find the difference in days:

long days = ChronoUnit.DAYS.between(date1.toInstant(), date2.toInstant());

Finally, you can compare if the difference is greater than 7 for a week. You can also apply the same logic for months, but you need to define how many days you will consider in a month.

Upvotes: 1

Related Questions