I have written the following code to find days between two dates
startDateValue = new Date(startDate);
endDateValue = new Date(endDate);
long diff = endDateValue.getTime() - startDateValue.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = (hours / 24) + 1;
Log.d("days", "" + days);
When start and end date are 2/3/2017 and 3/3/2017 respectively the number of days showing is 29.Though when they are of the same day it is showing 1.(The number of days one takes a leave.So if one takes a single day leave,he has to select same start and end date.So in this case he has taken two days leave).
What am I doing wrong? Thank you for your time.
Note: Please don't use the date constructor. Check the accepted answer below. Use simpledateformat or Joda time. Date constructor is deprecated.
What date format do you use? Is it
d/M/yyyy
orM/d/yyyy
?d = day, M = month, yyyy = year
(see: https://developer.android.com/reference/java/text/SimpleDateFormat.html)
Then the codes:
And for
getUnitBetweenDates
method:Your code for generating date object:
You are getting 28 days as answer because according to
Date(String)
constructor it is thinking day = 3,month = 2 and year = 2017You can convert String to Date as follows:
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:
Please check link
If you use Joda Time it is much more simple:
Please check JodaTime
How to use JodaTime in Java Project
Does
Android
fully supportjava-8
? If yes you can simple useChronoUnit
classor same thing using formatter
Be carefur if you'd like to use received integer e.g. to indicate specific day in custom calendar implementation. For example, I tried to go in m app from monthly calendar view to daily view and show daily content, by calculating dates from 1970-01-01 to selected one, and each 25-31th day of month shows me as one day earlier, because
datesDifferenceInMillis / (24 * 60 * 60 * 1000);
may return something like 17645,95833333333, and casting this to int you'll get value lower by 1. In this case correctly number of days you'll get by rounding received float by using NumberFormat class. Here's my code:I hope it will be helpful.
Kotlin
Here is the example to calculate days from today to some date:
If you want to calculate two days, then change:
should work.
Very simple, just use Calendar, create two instances for the two dates, convert to milliseconds, subtract and convert to days (rounded up)... like this, basically: