Android calculate days between two dates
Does Android
fully support java-8
? If yes you can simple use ChronoUnit
class
LocalDate start = LocalDate.of(2017,2,3);
LocalDate end = LocalDate.of(2017,3,3);
System.out.println(ChronoUnit.DAYS.between(start, end)); // 28
or same thing using formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy");
LocalDate start = LocalDate.parse("2/3/2017",formatter);
LocalDate end = LocalDate.parse("3/3/2017",formatter);
System.out.println(ChronoUnit.DAYS.between(start, end)); // 28
public static int getDaysDifference(Date fromDate,Date toDate)
{
if(fromDate==null||toDate==null)
return 0;
return (int)( (toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24));
}
Your code for generating date object:
Date date = new Date("2/3/2017"); //deprecated
You are getting 28 days as answer because according to Date(String)
constructor it is thinking day = 3,month = 2 and year = 2017
You can convert String to Date as follows:
String dateStr = "2/3/2017";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse(dateStr);
Use above template to make your Date object. Then use below code for calculating days in between two dates. Hope this clear the thing.
It can de done as follows:
long diff = endDateValue.getTime() - startDateValue.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
Please check link
If you use Joda Time it is much more simple:
int days = Days.daysBetween(date1, date2).getDays();
Please check JodaTime
How to use JodaTime in Java Project
Kotlin
Here is the example to calculate days from today to some date:
val millionSeconds = yourDate.time - Calendar.getInstance().timeInMillis
leftDays.text = TimeUnit.MILLISECONDS.toDays(millionSeconds).toString() + "days"
If you want to calculate two days, then change:
val millionSeconds = yourDate1.time - yourDate2.time
should work.