Is it possible to add weekdays to joda time?
For instance, if current date is Friday 01/03, date + 1 should return Monday 04/03, rather than 02/03.
As far as I know there is no built-in method to automatically do this for you in Joda Time. However, you could write your own method, that increments the date in a loop until you get to a weekday.
Note that, depending on what you need it for exactly, this could be (much) more complicated than you think. For example, should it skip holidays too? Which days are holidays depends on which country you're in. Also, in some countries (for example, Arabic countries) the weekend is on Thursday and Friday, not Saturday and Sunday.
LocalDate newDate = new LocalDate();
int i=0;
while(i<days)//days == as many days as u want too
{
newDate = newDate.plusDays(1);//here even sat and sun are added
//but at the end it goes to the correct week day.
//because i is only increased if it is week day
if(newDate.getDayOfWeek()<=5)
{
i++;
}
}
System.out.println("new date"+newDate);
Be aware that iterating through adding N days one at a time can be relatively expensive. For small values of N and/or non performance sensitive code, this is probably not an issue. Where it is, I'd recommend minimizing the add operations by working out how many weeks and days you need to adjust by:
/**
* Returns the date that is {#code n} weekdays after the specified date.
* <p>
* Weekdays are Monday through Friday.
* <p>
* If {#code date} is a weekend, 1 weekday after is Monday.
*/
public static LocalDate weekdaysAfter(int n, LocalDate date) {
if (n == 0)
return date;
if (n < 0)
return weekdaysBefore(-n, date);
LocalDate newDate = date;
int dow = date.getDayOfWeek();
if (dow >= DateTimeConstants.SATURDAY) {
newDate = date.plusDays(8 - dow);
n--;
}
int nWeeks = n / 5;
int nDays = n % 5;
newDate = newDate.plusWeeks(nWeeks);
return ( (newDate.getDayOfWeek() + nDays) > DateTimeConstants.FRIDAY)
? newDate.plusDays(nDays + 2)
: newDate.plusDays(nDays);
public LocalDate getBusinessDaysAddedDate(LocalDate localDate, int businessDays){
LocalDate result;
if(localDate.getDayOfWeek().getValue() + businessDays > 5) {
result = localDate.plusDays(2);
}
result = localDate.plusDays(businessDays);
return result;
}
In order to work with Date instead of LocalDate, refer https://stackoverflow.com/a/47719540/12794444 for the conversions.
Class YearMonthDay is deprecated and you shouldn't use it. If you change to simple DateTime you can obtain the week day by calling:
dateTime.getDayOfWeek();
For Friday it will be 5.
One of the approaches can be making a custom addDays method which should look something like that:
addDays(DateTime dateTime, int days) {
for(int i=0;i<days;i++){
dateTime.plusDays(1);
if(dateTime.getDayOfWeek()==6) dateTime.plusDays(2); // if Saturday add 2 more days }
}
Related
I'm trying to set up constraints for a Material Date Range Picker Dialog. The idea is to limit the range of the selectable dates from the current day to the same day one month later.
I have a method to build the constraints:
public CalendarConstraints.Builder setCalendarConstraints() {
CalendarConstraints.Builder constraints = new CalendarConstraints.Builder();
long min = setMinDate();
long max = setMaxDate();
constraints.setStart(min);
constraints.setEnd(max);
return constraints;
}
And the two following methods are used to get the minimum and maximum dates:
// Maximum date for the date picker is the current date + 1 month
public long setMaxDate() {
LocalDate now = LocalDate.now();
LocalDate max;
if (now.getMonthValue() == 12) {
max = LocalDate.of(now.getYear(), 1, now.getDayOfMonth());
max.plusYears(1);
} else {
max = LocalDate.of(now.getYear(), now.getMonth().plus(1), now.getDayOfMonth());
}
return max.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli();
}
Everything was working when I was testing my app two weeks ago, so I think the problem comes from that we are now in December. I tried to add a year to the current year when we are in December, when it looks like it doesn't work as I have the following error:
java.lang.IllegalArgumentException: current Month cannot be after end Month
The java.time classes use immutable objects.
The method LocalDate::plusYears() doesn't work on the LocalDate itself. As the Javadoc says, it returns a new object, a copy of the original LocalDate Object but with with one year added.
So you'll need to write:
max = max.plusYears(1);
By the way, you don't need to check for December.
LocalDate max = LocalDate.now().plusMonths(1)
does the trick whether you're in December or not.
try
LocalDate.now().plusMonths( 1 );
for max
I want to use the difference method.
It gets a certain date parameter, then calculates the difference between two dates (this and other)
The calculateDate is the way to get the days passed since the Christian counting. I wanted to use it inside the difference method, but I get the following error while trying to compile:
cannot find symbol - variable calculateDate
The difference has to be an absolute value, so I added the Math.abs.
public int difference (Date other) {
return Math.abs(this.calculateDate-other.calculateDate);
}
//computes the day number since the beginning of the Christian counting of years
private int calculateDate (int day, int month, int year)
{
if (month < 3)
{
year--;
month = month + 12;
}
return 365 * year + year/4 - year/100 + year/400 + ((month+1) * 306)/10 + (day - 62);
}
It would be easier to use java.time library instead of writing the day counting code by hand, unless you have a very specific requirement:
private int difference(LocalDate date) {
LocalDate start = LocalDate.of(0, 1, 1); // 1 Jan 0000
return ChronoUnit.DAYS.between(start, date);
}
You can map from java.util.Date to java.time.LocalDate with:
Date date = ...
LocalDate ld = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
I'm pretty new to Java world, and I'm practicing a lot.
My last exercize is about an Apartment Renting program. My question refers to the "booking" part in the Manager class, in which I have to check if the requested arrival date is linked to the low, medium or high season lot in the array double tariffs[].
Here is the portion of code with the bookApartment() method, where code and id are the keys in the HashMaps of Apartments and Clients (booking is correct only if the arrival date is a Saturday):
public Booking bookAppartment(String code, String id, int day, int month, int year, int nweeks) throws WrongDay {
Calendar date = Calendar.getInstance();
date.set(year, month-1, day);
int weekday = date.get(Calendar.DAY_OF_WEEK);
Booking book=null;
if(code!="" && id!=""){
if(weekday!=Calendar.SATURDAY)
throw new WrongDay(date);
else{
for(Map.Entry<String , Apartment> apt : apts.entrySet()){
for(Map.Entry<String, Client> client : clients.entrySet()){
if(apt.getKey()==code && client.getKey()==id && weekday==Calendar.SATURDAY){
book = new Booking(client.getValue(), apt.getValue(), d, m, y, nweeks);
bookings.add(book);
book.setPrice(d, m, y, apt.getValue().getTariffs(), nweeks);
break;
}
}
}
}
}
return book;
}
And here I attach the constructor of the Booking object and my personal override of the setPrice() method, which calculates the entire booking price selecting the correct tariffs[] lot:
public class Booking {
private Client client;
private Apartment apt;
private double price;
private int numweeks;
private static int day, month, year;
public Booking(Client client, Apartment apt, int day, int month, int year, int numweeks){
this.client = client;
this.apt = apt;
Booking.day = day;
Booking.month = month;
Booking.year = year;
this.numweeks = numweeks;
}
// other stuff
public void setPrice(int day, int month, int year, double[] tariff, int numweeks){
tariff = apt.getTariffs();
Booking.day=day;
Booking.month=month;
Booking.year=year;
Calendar date = Calendar.getInstance();
date.set(year, month-1, day);
Calendar date1 = Calendar.getInstance();
date1.set(2008, 6, 1);
Calendar date2 = Calendar.getInstance();
date2.set(2008, 6, 31);
Calendar date3 = Calendar.getInstance();
date3.set(2008, 7, 1);
Calendar date4 = Calendar.getInstance();
date4.set(2008, 7, 31);
Calendar date5 = Calendar.getInstance();
date5.set(2008, 11, 20);
Calendar date6 = Calendar.getInstance();
date6.set(2009, 0, 1);
if(date.equals(date1) || date.equals(date2) || (date.after(date1) && date.before(date2))){
this.price = tariff[1] * numweeks;
} else if(date.equals(date3) || date.equals(date4) || (date.after(date3) && date.before(date4))){
this.price = tariff[2] * numweeks;
} else if(date.equals(date5) || date.equals(date6) || (date.after(date5) && date.before(date6))){
this.price = tariff[2] * numweeks;
} else{
this.price = tariff[0] * numweeks;
}
}
}
I encounter the problem when setting the price of a Booking object with arrival date on the 20th December 2008 (considered high season): it skips the third if check (expected) and goes directly to the last else.
But if I run my own program to check if the dates are the same, passing directly the values to day, month and year, the test is passed.
So it seems to me that I cannot pass only references not pointing to an int value not manually setted.
Is it possible I am right?
If so, I really don't know how to go on.
Thanks in advance: I hope I used all the right words in the right places.
When you get a calendar instance, it defaults to using the current time (right down to the millisecond). Thus, when set your date in it:
Calendar date = Calendar.getInstance();
date.set(year, month-1, day);
... the date is still left with "random" values for the hours, minutes, seconds and milliseconds. The same goes for date1 through to date6.
In your code, you create all the dates one right after the other, so the speed of executing those instructions may mean that the first few dates end up with identical values for hours, minutes, seconds and milliseconds. However there is no guarantee of this.
What you're finding is that when you do, for example, date.equals(date3), the year month and day match, but the other fields potentially don't.
To solve this, call clear() first:
Calendar date = Calendar.getInstance();
date.clear();
date.set(year, month-1, day);
Also, you probably don't actually want to compare calendars for equality. You can, but if you look at the Javadoc for it, it says:
* Compares this <code>Calendar</code> to the specified
* <code>Object</code>. The result is <code>true</code> if and only if
* the argument is a <code>Calendar</code> object of the same calendar
* system that represents the same time value (millisecond offset from the
* Epoch) under the same
* <code>Calendar</code> parameters as this object.
*
* <p>The <code>Calendar</code> parameters are the values represented
* by the <code>isLenient</code>, <code>getFirstDayOfWeek</code>,
* <code>getMinimalDaysInFirstWeek</code> and <code>getTimeZone</code>
* methods. If there is any difference in those parameters
* between the two <code>Calendar</code>s, this method returns
* <code>false</code>.
*
* <p>Use the {#link #compareTo(Calendar) compareTo} method to
* compare only the time values.
You're probably better off using:
if (date.getTime().equals(date1.getTime()))
{
...
}
... and comparing the returned Date objects, or doing as the Javadoc suggests and using compareTo():
if (date.compareTo(date1) == 0)
{
...
}
I understand you are doing an exercise, but you should know:
(a) Avoid java.util.Calendar
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them. Use either the new java.time package bundled with Java 8, or the Joda-Time library which inspired java.time. Both java.time and Joda-Time have some pros and cons over each other, both are active projects, and you can even use them both in a project.
(b) Date-Only
The old .Date & .Calendar classes lack a representation of date-only without a time-of-day. But that is what your Question demands, a class that is date-only without time and time zones. Fortunately both Joda-Time and java.time have such a class, both called LocalDate.
(c) Half-Open
The best approach to spans of time is called "Half-Open" where the beginning is inclusive and the ending exclusive. For example the month of June would be June 1 and going up to, but not including, July 1. This simplifies things whether doing date-only or date-time work. Joda-Time and java.time adopt this approach.
The other answer by Greg Kopff seems to be correct, the time-of-day portion is throwing you off.
Here is some example code in Joda-Time 2.4 to get you headed in the right direction.
LocalDate target = new LocalDate( 2008, 12, 20 );
LocalDate highSummerStart = new LocalDate( 2008, 6, 1 ); // Half-Open. Inclusive.
LocalDate highSummerStop = new LocalDate( 2008, 7, 1 ); // Exclusive.
LocalDate lateSummerStart = new LocalDate( 2008, 7, 1 ); // Half-Open. Inclusive.
LocalDate lateSummerStop = new LocalDate( 2008, 8, 1 ); // Exclusive.
LocalDate holidaysStart = new LocalDate( 2008, 11, 20 ); // Half-Open. Inclusive.
LocalDate holidaysStop = new LocalDate( 2009, 1, 2 ); // Exclusive.
if ( this.rangeContainsTarget( highSummerStart, highSummerStop, target ) ) {
System.out.println( "Apply High Summer rates." );
} else if ( this.rangeContainsTarget( lateSummerStart, lateSummerStop, target ) ) {
System.out.println( "Apply Late Summer rates." );
} else if ( this.rangeContainsTarget( holidaysStart, holidaysStop, target ) ) {
System.out.println( "Apply Holidays rates." );
} else { // Else not in special season.
System.out.println( "Apply default rates." );
}
And the comparison method.
private boolean rangeContainsTarget( LocalDate start, LocalDate stop, LocalDate target )
{
// Half-Open approach. If the Target is GREATER THAN OR EQUAL TO Start AND Target is LESS THAN Stop.
if ( start.isAfter( stop ) ) {
return false; // Or throw exception.
}
boolean startGood = ( target.isEqual( start ) || target.isAfter( start ) );
boolean stopGood = target.isBefore( stop );
boolean containsTarget = ( startGood && stopGood );
return containsTarget;
}
The old .Date/.Calendar classes lack a way to represent a span of time. Joda-Time offers three classes to define a span of time in various ways: Interval, Period, and Duration. Unfortunately they work only with DateTime, not LocalDate. So I did not use them in the example above, where Interval would have been handy.
By the way, if in Joda-Time you do need a date plus time-of-day yet want to focus on days, call the withTimeAtStartOfDay() method to get a DateTime object set to the first moment of the day. That first moment is not always the time 00:00:00.000 because of Daylight Saving Time and perhaps other anomalies.
This question already has answers here:
Get the number of weeks between two Dates.
(19 answers)
Closed 8 years ago.
Let's see if you can help me. I want to get the number of weeks (starting on monday and finishing on sunday) between two dates, d1 and d2. Let's suppose that d2 is earlier of d1. That part of the code is already programmed and working. My problem now is that I'm not being able to code correctly the week program. This is what I made for now:
public static void getFullWeeks(Calendar d1, Calendar d2){
int Weeks = 0;
Calendar date2 = d2;
Calendar addWeek = GregorianCalendar.getInstance();
addWeek.setTime(date2.getTime());
addWeek.add(Calendar.DATE, 6);
while(addWeek.before(d1) || addWeek.equals(d1)){
if(date2.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY){
Weeks++;
}
date2.add(Calendar.DATE,1);
}
System.out.println(
"The number of weeks (from monday to sunday) between both dates are: "
+ Weeks);
}
But the output is "0 weeks", so the program is not working. What's wrong? I'm not encountering the error and I'm not being capable to find a working solution for this problem.
Thank you!!
In Java 8 without external libraries you can do something like the following:
*Edited to account for week starting on Monday
// TechTrip - ASSUMPTION d1 is earlier than d2
// leave that for exercise
public static long getFullWeeks(Calendar d1, Calendar d2){
// In Java the week starts on Sunday from an integral perspective
// public final static int SUNDAY = 1;
// SEQUENTIAL UP TO
// public final static int SATURDAY = 7;
// make the starting date relative to the Monday we need to calculate from
int dayOfStartWeek = d1.get(Calendar.DAY_OF_WEEK);
// IF we have a partial week we should add an offset that moves the start
// date UP TO the next Monday to simulate a week starting on Monday
// eliminating partial weeks from the calculation
// NOTE THIS METHOD WILL RETURN NEGATIVES IF D1 < D2 after adjusting for
// offset
if (dayOfStartWeek == Calendar.SUNDAY) {
// add an offset of 1 day because this is a partial week
d1.add(Calendar.DAY_OF_WEEK, 1);
} else if (dayOfStartWeek != Calendar.MONDAY){
// add an offset for the partial week
// Hence subtract from 9 accounting for shift by 1
// and start at 1
// ex if WEDNESDAY we need to add 9-4 (WED Int Val) = 5 days
d1.add(Calendar.DAY_OF_WEEK, 9 - dayOfStartWeek);
}
Instant d1i = Instant.ofEpochMilli(d1.getTimeInMillis());
Instant d2i = Instant.ofEpochMilli(d2.getTimeInMillis());
LocalDateTime startDate = LocalDateTime.ofInstant(d1i, ZoneId.systemDefault());
LocalDateTime endDate = LocalDateTime.ofInstant(d2i, ZoneId.systemDefault());
return ChronoUnit.WEEKS.between(startDate, endDate);
}
Here's the main:
public static void main(String[] args) {
Calendar d1 = Calendar.getInstance();
Calendar d2 = Calendar.getInstance();
d2.add(Calendar.WEEK_OF_YEAR, 6);
System.out.println(
"The number of weeks (from monday to sunday) between both dates are: "
+ getFullWeeks(d1, d2));
}
The output is as follows if the start date is a MONDAY:
The number of weeks (from monday to sunday) between both dates are: 6
Note, I did not assign date d2 to d1, making it the same reference. In that case you would get 0.
*The ChronoUnit takes a Temporal which is simply a date, time or offset. They must be of the same type. Temporals can be manipulated with plus and minus.
It seems to me there are couple of little mistakes you made:
1.) Your output is 0 weeks because elsewhere in your code you must have called this method with your first argument, d1, earlier than the second, while in the method body, you assume that d2 is earlier than d1. Such mistakes are easily avoided by using meaningful argument names. Appropriate argument names in this case are for example start and end.
2) If you execute this method using arguments in which d2 is earlier than d1, your method would fall into an infinite loop. It looks to me that adding to date2 does not change the date in addWeek.
3) Your method counts the number of weeks from Tuesday to Monday instead of Monday to Sunday. To fix this, add seven days to addWeek instead of six, or change the while loop to check only if addWeek is before d1 and increment weeks on sunday.
Putting all this together, I believe this will give you what you're looking for:
public static void getFullWeeks(Calendar start, Calendar end)
{
System.out.println("The number of weeks (from monday to sunday) between both dates are: " + getNrWeeksBetween(start, end));
}
private static int getNrWeeksBetween(Calendar start, Calendar end)
{
int weeks = 0;
Calendar counter = new GregorianCalendar();
counter.setTime( start.getTime() );
counter.add(Calendar.DATE, 6);
while( counter.before(end) )
{
if(counter.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) weeks++;
counter.add(Calendar.DATE, 1);
}
return weeks;
}
Your algorithm's wrong; your while loop needs to compare the same Calendar object you're modifying, but you don't do that, so you either have an infinite loop or you exit immediately with a return value of 0, depending on whether addDate is before or after d1 (since neither one changes). Your code should be:
public static void getFullWeeks(Calendar d1, Calendar d2){
int Weeks = 0;
Calendar addWeek = GregorianCalendar.getInstance();
addWeek.setTime(d2.getTime());
addWeek.add(Calendar.DATE, 6);
while(addWeek.before(d1) || addWeek.equals(d1)){
if(addWeek.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY){
Weeks++;
}
addWeek.add(Calendar.DATE,1);
}
System.out.println(
"The number of weeks (from monday to sunday) between both dates are: "
+ Weeks);
}
In java, I want to get the number of days between two dates, excluding those two dates.
For example:
If first date = 11 November 2011 and the second date = 13 November 2011
then it should be 1.
This is the code I am using but doesn't work (secondDate and firstDate are Calendar objects):
long diff=secondDate.getTimeInMillis()-firstDate.getTimeInMillis();
float day_count=(float)diff / (24 * 60 * 60 * 1000);
daysCount.setText((int)day_count+"");
I even tried rounding the results but that didn't help.
How do I get the number of days between dates in java excluding the days themselves?
I've just tested on SDK 8 (Android 2.2) the following code snippet:
Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();
date1.clear();
date1.set(
datePicker1.getYear(),
datePicker1.getMonth(),
datePicker1.getDayOfMonth());
date2.clear();
date2.set(
datePicker2.getYear(),
datePicker2.getMonth(),
datePicker2.getDayOfMonth());
long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
float dayCount = (float) diff / (24 * 60 * 60 * 1000);
textView.setText(Long.toString(diff) + " " + (int) dayCount);
it works perfectly and in both cases (Nov 10,2011 - Nov 8,2011) and (Nov 13,2011 - Nov 11,2011) gives dayCount = 2.0
Get Days between java.util.Dates, ignoring daylight savings time
Quick and dirty hack:
public int get_days_between_dates(Date date1, Date date2)
{
//if date2 is more in the future than date1 then the result will be negative
//if date1 is more in the future than date2 then the result will be positive.
return (int)((date2.getTime() - date1.getTime()) / (1000*60*60*24l));
}
This function will work 99.99% of the time, except when it surprises you later on in the edge cases during leap-seconds, daylight savings, timezone changes leap years and the like. If you are OK with the calculation being off by 1 (or 2) hours once in a while, this will suffice.
Get Days between Dates taking into account leapseconds, daylight savings, timezones, etc
If you are asking this question you need to slap yourself. What does it mean for two dates to be at least 1 day apart? It's very confusing. What if one Date is midnight in one timezone, and the other date is 1AM in another timezone? Depending on how you interpret it, the answer is both 1 and 0.
You think you can just force the dates you pass into the above function as Universal time format; that will fix some of your problems. But then you just relocate the problem into how you convert your local time to a universal time. The logical conversion from your timezone to universal time may not be what is intuitive. In some cases you will get a day difference when the dates passed in are obviously two days apart.
And you think you can deal with that? There are some simplistic calendar systems in the world which are constantly changing depending on the harvest season and installed political rulers. If you want to convert their time to UTC, java.util.Date is going to fail you at the worst moment.
If you need to calculate the days between dates and it is critical that everything come out right, you need to get an external library called Joda Time: (They have taken care of all the details for you, so you can stay blissfully unaware of them): http://joda-time.sourceforge.net/index.html
java.time
The java.time API, released with Java-8 in March 2014, supplanted the error-prone legacy date-time API. Since then, using this modern date-time API has been strongly recommended.
Solution using modern date-time API
Using Calendar#toInstant, convert your java.util.Calendar instances into java.time.Instant and then into java.time.ZonedDateTime instances and then use ChronoUnit.DAYS.between to get the number of days between them.
Demo:
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
// Sample start and end dates as java.util.Date
Calendar startCal = Calendar.getInstance();
startCal.set(2011, 10, 11); // 11 November 2011
Calendar endCal = Calendar.getInstance();
endCal.set(2011, 10, 13); // 13 November 2011
// Convert the java.util.Calendar into java.time.ZonedDateTime
// Replace ZoneId.systemDefault() with the applicable ZoneId
ZonedDateTime startDateTime = startCal.toInstant().atZone(ZoneId.systemDefault());
ZonedDateTime endDateTime = endCal.toInstant().atZone(ZoneId.systemDefault());
// The end date is excluded by default. Subtract 1 to exclude the start date
long days = ChronoUnit.DAYS.between(startDateTime, endDateTime) - 1;
System.out.println(days);
}
}
Output:
1
Learn more about the modern Date-Time API from Trail: Date Time.
Don't use floats for integer calculations.
Are you sure your dates are days? The precision of the Date type is milliseconds. So the first thing you need to do is round the date to something which doesn't have hours. Example: It's just one hour from 23:30 2011-11-01 to 00:30 2011-11-02 but the two dates are on different days.
If you are only going to be dealing with dates between the years 1900 and 2100, there is a simple calculation which will give you the number of days since 1900:
public static int daysSince1900(Date date) {
Calendar c = new GregorianCalendar();
c.setTime(date);
int year = c.get(Calendar.YEAR);
if (year < 1900 || year > 2099) {
throw new IllegalArgumentException("daysSince1900 - Date must be between 1900 and 2099");
}
year -= 1900;
int month = c.get(Calendar.MONTH) + 1;
int days = c.get(Calendar.DAY_OF_MONTH);
if (month < 3) {
month += 12;
year--;
}
int yearDays = (int) (year * 365.25);
int monthDays = (int) ((month + 1) * 30.61);
return (yearDays + monthDays + days - 63);
}
Thus, to get the difference in days between two dates, you calculate their days since 1900 and calc the difference. Our daysBetween method looks like this:
public static Integer getDaysBetween(Date date1, Date date2) {
if (date1 == null || date2 == null) {
return null;
}
int days1 = daysSince1900(date1);
int days2 = daysSince1900(date2);
if (days1 < days2) {
return days2 - days1;
} else {
return days1 - days2;
}
}
In your case you would need to subtract an extra day (if the days are not equal).
And don't ask me where this calculation came from because we've used it since the early '90s.
I have two suggestions:
Make sure your float day_count is calculated correctly
float day_count = ((float)diff) / (24f * 60f * 60f * 1000f);
If it's rounding error, try using floor method
daysCount.setText("" + (int)Math.floor(day_count));