th3ramr0d th3ramr0d - 1 month ago 5
Android Question

Number of days between two dates not based on time

I save a date and then compare that against the current date using

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
introDateTimeSaved = formatter.parseDateTime(introDateViewedString);
introDays = Days.daysBetween(introTodaysDate, introDateTimeSaved);


in order to determine how many days it has been since the saved date has been updated. This is to show how long ago a particular button has been pressed. The problem is that the days goes off of 24 hours and I want it to go off purely days. For instance:

Saved Date Variable: 2016-10-15 08:26:00

Today Date Variable 2016-10-16 08:25:00

This returns a difference in days of 0 and my best guess is because the time between these two dates is 23 hours and 59 minutes. I want this to return 1 since its a difference of 1 day from the 15th to the 16th or return 2 if its the 14th and today is the 16th ect etc.

Answer

You could use the difference in hours intead, then divide by 24 and round down.

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
introDateTimeSaved = formatter.parseDateTime(introDateViewedString);

Period p = new Period(introDateTimeSaved, introTodaysDate);
int hours = p.getHours();
int days =  Math.floor(hours/24.0);

EDIT:

Interval was calculated using Joda Time library as the JDK Date API is horrible to manipulate.

Comments