Android Days between two dates
Solution 1
Please refer this code, this may help you.
public String getCountOfDays(String createdDateString, String expireDateString) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
Date createdConvertedDate = null, expireCovertedDate = null, todayWithZeroTime = null;
try {
createdConvertedDate = dateFormat.parse(createdDateString);
expireCovertedDate = dateFormat.parse(expireDateString);
Date today = new Date();
todayWithZeroTime = dateFormat.parse(dateFormat.format(today));
} catch (ParseException e) {
e.printStackTrace();
}
int cYear = 0, cMonth = 0, cDay = 0;
if (createdConvertedDate.after(todayWithZeroTime)) {
Calendar cCal = Calendar.getInstance();
cCal.setTime(createdConvertedDate);
cYear = cCal.get(Calendar.YEAR);
cMonth = cCal.get(Calendar.MONTH);
cDay = cCal.get(Calendar.DAY_OF_MONTH);
} else {
Calendar cCal = Calendar.getInstance();
cCal.setTime(todayWithZeroTime);
cYear = cCal.get(Calendar.YEAR);
cMonth = cCal.get(Calendar.MONTH);
cDay = cCal.get(Calendar.DAY_OF_MONTH);
}
/*Calendar todayCal = Calendar.getInstance();
int todayYear = todayCal.get(Calendar.YEAR);
int today = todayCal.get(Calendar.MONTH);
int todayDay = todayCal.get(Calendar.DAY_OF_MONTH);
*/
Calendar eCal = Calendar.getInstance();
eCal.setTime(expireCovertedDate);
int eYear = eCal.get(Calendar.YEAR);
int eMonth = eCal.get(Calendar.MONTH);
int eDay = eCal.get(Calendar.DAY_OF_MONTH);
Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();
date1.clear();
date1.set(cYear, cMonth, cDay);
date2.clear();
date2.set(eYear, eMonth, eDay);
long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
float dayCount = (float) diff / (24 * 60 * 60 * 1000);
return ("" + (int) dayCount + " Days");
}
Solution 2
Here's a two line solution:
long msDiff = Calendar.getInstance().getTimeInMillis() - testCalendar.getTimeInMillis();
long daysDiff = TimeUnit.MILLISECONDS.toDays(msDiff);
In this example it gets the number of days between date "testCalendar" and the current date.
Solution 3
I've finally found the easiest way to deal with that. Here is my code:
public int getTimeRemaining()
{
Calendar sDate = toCalendar(this.dateEvent);
Calendar eDate = toCalendar(System.currentTimeMillis());
// Get the represented date in milliseconds
long milis1 = sDate.getTimeInMillis();
long milis2 = eDate.getTimeInMillis();
// Calculate difference in milliseconds
long diff = Math.abs(milis2 - milis1);
return (int)(diff / (24 * 60 * 60 * 1000));
}
private Calendar toCalendar(long timestamp)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestamp);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
Hope it helps.
Solution 4
You should never use formula such 24 * 60 * 60 * 1000! Why? Because there is day saving time, and not all days have 24 hours, also what about leap year, that has +1 day. That's why there is a calendar class. If you do not want to put any external library to your project like Jodatime, you could use pure Calendar class with very efficient function:
public static int numDaysBetween(final Calendar c, final long fromTime, final long toTime) {
int result = 0;
if (toTime <= fromTime) return result;
c.setTimeInMillis(toTime);
final int toYear = c.get(Calendar.YEAR);
result += c.get(Calendar.DAY_OF_YEAR);
c.setTimeInMillis(fromTime);
result -= c.get(Calendar.DAY_OF_YEAR);
while (c.get(Calendar.YEAR) < toYear) {
result += c.getActualMaximum(Calendar.DAY_OF_YEAR);
c.add(Calendar.YEAR, 1);
}
return result;
}
Solution 5
public long Daybetween(String date1,String date2,String pattern)
{
SimpleDateFormat sdf = new SimpleDateFormat(pattern,Locale.ENGLISH);
Date Date1 = null,Date2 = null;
try{
Date1 = sdf.parse(date1);
Date2 = sdf.parse(date2);
}catch(Exception e)
{
e.printStackTrace();
}
return (Date2.getTime() - Date1.getTime())/(24*60*60*1000);
}
Manitoba
Updated on April 14, 2021Comments
-
Manitoba about 3 years
I want to compare two dates for my Android application, but I got a really weird issue.
For example:
If I set the
back in the past
date to 127 days ago:this.dateEvent = System.currentTimeMillis() - (127 * 24 * 3600 * 1000)
And then compare it to the current date (Days between)
Calendar sDate = getDatePart(new Date(this.dateEvent)); Calendar eDate = getDatePart(new Date(System.currentTimeMillis())); int daysBetween = 0; while (sDate.before(eDate)) { sDate.add(Calendar.DAY_OF_MONTH, 1); daysBetween ++; } while (sDate.after(eDate)) { eDate.add(Calendar.DAY_OF_MONTH, 1); daysBetween ++; } return daysBetween;
It will return 22 which is not at all what was expected.
Did I make something wrong or is that an issue with the
Calendar
class ? -
Manitoba about 10 yearsHello, thanks bug that won't work if
date1
points to the same date asdate2
-
Bram over 9 yearsExactly what I was looking for. Thanks!
long diff = date2.getTimeInMillis() - date1.getTimeInMillis(); float dayCount = (float) diff / (24 * 60 * 60 * 1000);
-
ePeace over 8 yearsThis worked for me after i changed Calendar.HOUR to Calendar.HOUR_OF_DAY
-
Lior Iluz over 8 yearsJoda time library will add 4744 methods to your project. Choose wisely if you want to avoid the 65K methods limit.
-
sud007 over 8 yearsAdding jars is really unwise, just for a simple calculation. Be wary of methods limit as @LiorIluz mentioned.
-
statosdotcom about 7 yearsBut this can be faked if the user manually changes device date... how to workaround it?
-
Tobias Reich almost 7 yearsAh, just what I was looking for. Thanks!
-
Rodrigo Gontijo almost 6 yearsThis is the best answer !
-
Bogy over 4 yearsYou should test your solution before posting it, there is a copy/past error and a typo in Calendar
-
Ole V.V. about 4 yearsOne more confusing trait of the poorly designed
Calendar
class:HOUR
does not meanHOUR_OF_DAY
. @ePeace -
7200rpm about 4 yearsUpdate, java.time is now available native for API <26 without ThreeTehnABP. You just need to use Android 4.0 and add in some simple config: developer.android.com/studio/preview/features#j8-desugar
-
gunjot singh almost 4 yearswooooow !! Thank you :)
-
Ole V.V. almost 4 yearsUsing java.time is a good idea (as I also recommend in my answer). Your way of doing it won’t always be accurate, though.
Duration
assumes that a day is always 24 hours. A day is not always 24 hours. The typical counter-example is the spring forward, where a day is only 23 hours. If your interval is across this spring forward, you will be counting one day too few even whenstartDate
andendDate
have the same time of day. -
postfixNotation almost 4 yearsHi and thanks a lot for your helpful comment! I just edited my answer, setting both values to a UTC-zoned value. Do you think this might solve the issue, I mean setting both to UTC to simply get the correct number of days in between? Thx!
-
Ole V.V. almost 4 yearsSorry, it’s not OK . I have set my time zone to Europe/Berlin. I have two
Date
objects, Sun Mar 29 01:30:00 CET 2020 and Mon Mar 30 01:30:00 CEST 2020. You see that the time of day is the same. Expected number of days between: 1. Days between according to your method: 0. -
Ole V.V. almost 4 yearsYou may use
ChronoUnit.DAYS.between(startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(), endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
. Feel free to publish in your answer, and I will upvote. You may of course wrap the conversion fromDate
toLocalDate
into an auxiliary method in the same manner as you already do. -
postfixNotation almost 4 yearsThanks for your helpful comments! I tried the following:
val zoneId = ZoneId.systemDefault()
,val date1 = LocalDateTime.of(2020, Month.MARCH, 29, 1, 30, 0, 0)
,val date2 = LocalDateTime.of(2020, Month.MARCH, 30, 1, 30, 0, 0)
,val zonedDate1 = ZonedDateTime.of(date1, zoneId)
,val zonedDate2 = ZonedDateTime.of(date2, zoneId)
which leas to 0 days in between since I'm in Berlin:Duration.between(zonedDate1, zonedDate2).toDays()
-
postfixNotation almost 4 yearsBut if I do the same with
ZoneId.of("UTC")
as zoneId I get the correct result of 1 day. In the above method of my answer theinstant.atZone(ZoneOffset.UTC)
is actually meant as a constant (always UTC). So I was not intending to have this as a variable. -
postfixNotation almost 4 yearsAs far as I know a
Date
object doesn't store the time zone at all, it's basically a point in time, completely time zone agnostic. I might be wrong, or I simply don't understand the issue you are describing. -
Ole V.V. almost 4 yearsYou are correct, a
Date
is a point in time independent of time zone. -
Amir Hossein Ghasemi almost 4 yearsit have issue on day light saving timezones
-
Ole V.V. over 3 yearsI am probably repeating myself. (1) the classes
Calendar
andDate
are poorly designed and long outdated, I recommend that you don’t use them. (2) Your calculation assumes there are always 24 hours in a day. A day can be occasionally shorter, e.g., 23 hours, so your code will count 1 day too few sometimes. -
coding.cat3 about 3 yearsworked like a charm in the way i wanted to , thanks !
-
Izhan Ali almost 3 years@statosdotcom set date in your server in unix format and update it daily