Android / Java - date difference in days

I get the current date (in 12/31/1999 format, i.e. mm / dd / yyyy) using the following code:

Textview txtViewData; txtViewDate.setText("Today is " + android.text.format.DateFormat.getDateFormat(this).format(new Date())); 

and I have a different date in the format: 2010-08-25 (i.e. yyyy / mm / dd),

so I want to find the difference between the date in the number of days, how can I find the difference in days?

(In other words, I want to find the difference between CURRENT DATE - yyyy / mm / dd formatted date )

+68
java android date
01 Oct '10 at 10:59
source share
17 answers

Not a really reliable method, it is better to use JodaTime

  Calendar thatDay = Calendar.getInstance(); thatDay.set(Calendar.DAY_OF_MONTH,25); thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less thatDay.set(Calendar.YEAR, 1985); Calendar today = Calendar.getInstance(); long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis 

Here's an approximation ...

 long days = diff / (24 * 60 * 60 * 1000); 

To parse a date from a string, you can use

  String strThatDay = "1985/08/25"; SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); Date d = null; try { d = formatter.parse(strThatDay);//catch exception } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Calendar thatDay = Calendar.getInstance(); thatDay.setTime(d); //rest is the same.... 

Although, since you are sure about the date format ... You can also do Integer.parseInt() on it Substrings to get their numeric values.

+115
01 Oct '10 at 11:18
source share

This is NOT my job, found the answer here . in the future I would not like to have a broken link :).

The key is this line for daylight accounting, the complete code.

 TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); 

or try passing TimeZone as the daysBetween() parameter and call setTimeZone() on the sDate and eDate .

So here it is:

 public static Calendar getDatePart(Date date){ Calendar cal = Calendar.getInstance(); // get calendar instance cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); // set hour to midnight cal.set(Calendar.MINUTE, 0); // set minute in hour cal.set(Calendar.SECOND, 0); // set second in minute cal.set(Calendar.MILLISECOND, 0); // set millisecond in second return cal; // return the date part } 

getDatePart () taken from here

 /** * This method also assumes endDate >= startDate **/ public static long daysBetween(Date startDate, Date endDate) { Calendar sDate = getDatePart(startDate); Calendar eDate = getDatePart(endDate); long daysBetween = 0; while (sDate.before(eDate)) { sDate.add(Calendar.DAY_OF_MONTH, 1); daysBetween++; } return daysBetween; } 

Nuances: Finding the difference between two dates is not as easy as subtracting two dates and dividing the result by (24 * 60 * 60 * 1000). Infact, its wrong!

For example: The difference between the two dates 03/24/2007 and 03/25/2007 should be 1 day; However, using the above method, in the UK you will get 0 days!

See for yourself (code below). Switching to the millisecond will cause errors to be rounded, and they will become most obvious as soon as you have a small thing, for example, โ€œDaylight saving timeโ€.

Full code:

 import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class DateTest { public class DateTest { static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); public static void main(String[] args) { TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); //diff between these 2 dates should be 1 Date d1 = new Date("01/01/2007 12:00:00"); Date d2 = new Date("01/02/2007 12:00:00"); //diff between these 2 dates should be 1 Date d3 = new Date("03/24/2007 12:00:00"); Date d4 = new Date("03/25/2007 12:00:00"); Calendar cal1 = Calendar.getInstance();cal1.setTime(d1); Calendar cal2 = Calendar.getInstance();cal2.setTime(d2); Calendar cal3 = Calendar.getInstance();cal3.setTime(d3); Calendar cal4 = Calendar.getInstance();cal4.setTime(d4); printOutput("Manual ", d1, d2, calculateDays(d1, d2)); printOutput("Calendar ", d1, d2, daysBetween(cal1, cal2)); System.out.println("---"); printOutput("Manual ", d3, d4, calculateDays(d3, d4)); printOutput("Calendar ", d3, d4, daysBetween(cal3, cal4)); } private static void printOutput(String type, Date d1, Date d2, long result) { System.out.println(type+ "- Days between: " + sdf.format(d1) + " and " + sdf.format(d2) + " is: " + result); } /** Manual Method - YIELDS INCORRECT RESULTS - DO NOT USE**/ /* This method is used to find the no of days between the given dates */ public static long calculateDays(Date dateEarly, Date dateLater) { return (dateLater.getTime() - dateEarly.getTime()) / (24 * 60 * 60 * 1000); } /** Using Calendar - THE CORRECT WAY**/ public static long daysBetween(Date startDate, Date endDate) { ... } 

OUTPUT:

Manually - Days between: 01-Jan-2007 and 02-Jan-2007: 1

Calendar - Days between: 01-Jan-2007 and 02-Jan-2007: 1




Leadership - Days Between: March 24, 2007 and March 25, 2007: 0

Calendar - Days between: March 24, 2007 and March 25, 2007: 1

+74
Jun 20 '11 at 2:18
source share

Most of the answers were good and correct for your problem.

so I want to find the difference between the date in the number of days, how can I find the difference in days?

I suggest this simple and straightforward approach that is guaranteed to give you the right difference in any time zone:

 int difference= ((int)((startDate.getTime()/(24*60*60*1000)) -(int)(endDate.getTime()/(24*60*60*1000)))); 

What is it!

+32
Sep 29 '13 at 15:53
source share

Use jodatime API

 Days.daysBetween(start.toDateMidnight() , end.toDateMidnight() ).getDays() 

where "start" and "end" are your DateTime objects. To parse your date Strings into DateTime objects use the parseDateTime method

There is also a special JodaTime library for Android .

+23
01 Oct 2018-10-10
source share

This fragment takes into account summer time and is equal to O (1).

 private final static long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000; private static long getDateToLong(Date date) { return Date.UTC(date.getYear(), date.getMonth(), date.getDate(), 0, 0, 0); } public static int getSignedDiffInDays(Date beginDate, Date endDate) { long beginMS = getDateToLong(beginDate); long endMS = getDateToLong(endDate); long diff = (endMS - beginMS) / (MILLISECS_PER_DAY); return (int)diff; } public static int getUnsignedDiffInDays(Date beginDate, Date endDate) { return Math.abs(getSignedDiffInDays(beginDate, endDate)); } 
+14
Feb 21 2018-12-21T00:
source share

This is the simplest and best calculation for me and may be for you.

  try { /// String CurrDate= "10/6/2013"; /// String PrvvDate= "10/7/2013"; Date date1 = null; Date date2 = null; SimpleDateFormat df = new SimpleDateFormat("M/dd/yyyy"); date1 = df.parse(CurrDate); date2 = df.parse(PrvvDate); long diff = Math.abs(date1.getTime() - date2.getTime()); long diffDays = diff / (24 * 60 * 60 * 1000); System.out.println(diffDays); } catch (Exception e1) { System.out.println("exception " + e1); } 
+5
Oct 11 '13 at 10:07 on
source share

Correct Way from the Sam Quest answer only works if the first date was earlier than the second. Moreover, it will return 1 if there are two dates in one day.

This is the best solution for me. Like most other solutions, it will still show incorrect results for two days a year due to incorrect daylight shifts.

 private final static long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000; long calculateDeltaInDays(Calendar a, Calendar b) { // Optional: avoid cloning objects if it is the same day if(a.get(Calendar.ERA) == b.get(Calendar.ERA) && a.get(Calendar.YEAR) == b.get(Calendar.YEAR) && a.get(Calendar.DAY_OF_YEAR) == b.get(Calendar.DAY_OF_YEAR)) { return 0; } Calendar a2 = (Calendar) a.clone(); Calendar b2 = (Calendar) b.clone(); a2.set(Calendar.HOUR_OF_DAY, 0); a2.set(Calendar.MINUTE, 0); a2.set(Calendar.SECOND, 0); a2.set(Calendar.MILLISECOND, 0); b2.set(Calendar.HOUR_OF_DAY, 0); b2.set(Calendar.MINUTE, 0); b2.set(Calendar.SECOND, 0); b2.set(Calendar.MILLISECOND, 0); long diff = a2.getTimeInMillis() - b2.getTimeInMillis(); long days = diff / MILLISECS_PER_DAY; return Math.abs(days); } 
+3
Jan 31 '12 at 16:34
source share

the best and easiest way to do it

  public int getDays(String begin) throws ParseException { long MILLIS_PER_DAY = 24 * 60 * 60 * 1000; SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH); long begin = dateFormat.parse(begin).getTime(); long end = new Date().getTime(); // 2nd date want to compare long diff = (end - begin) / (MILLIS_PER_DAY); return (int) diff; } 
+3
Feb 04 '16 at 13:18
source share

Use the following functions:

  /** * Returns the number of days between two dates. The time part of the * days is ignored in this calculation, so 2007-01-01 13:00 and 2007-01-02 05:00 * have one day inbetween. */ public static long daysBetween(Date firstDate, Date secondDate) { // We only use the date part of the given dates long firstSeconds = truncateToDate(firstDate).getTime()/1000; long secondSeconds = truncateToDate(secondDate).getTime()/1000; // Just taking the difference of the millis. // These will not be exactly multiples of 24*60*60, since there // might be daylight saving time somewhere inbetween. However, we can // say that by adding a half day and rounding down afterwards, we always // get the full days. long difference = secondSeconds-firstSeconds; // Adding half a day if( difference >= 0 ) { difference += SECONDS_PER_DAY/2; // plus half a day in seconds } else { difference -= SECONDS_PER_DAY/2; // minus half a day in seconds } // Rounding down to days difference /= SECONDS_PER_DAY; return difference; } /** * Truncates a date to the date part alone. */ @SuppressWarnings("deprecation") public static Date truncateToDate(Date d) { if( d instanceof java.sql.Date ) { return d; // java.sql.Date is already truncated to date. And raises an // Exception if we try to set hours, minutes or seconds. } d = (Date)d.clone(); d.setHours(0); d.setMinutes(0); d.setSeconds(0); d.setTime(((d.getTime()/1000)*1000)); return d; } 
+2
01 Oct '10 at 11:02
source share

There a simple solution, at least for me, is the only possible solution.

The problem is that all the answers that I see are thrown around - using Joda, or Calendar, or Date, or something else - consider only milliseconds. In the end, they count the number of 24-hour cycles between two dates , not the actual number of days . So from January 1, 11:00 to January 2, 1:00 0 days will return.

To calculate the actual number of days between startDate and endDate , simply do:

 // Find the sequential day from a date, essentially resetting time to start of the day long startDay = startDate.getTime() / 1000 / 60 / 60 / 24; long endDay = endDate.getTime() / 1000 / 60 / 60 / 24; // Find the difference, duh long daysBetween = endDay - startDay; 

This will return "1" between January 2 and January 1. If you need to calculate the end of the day, just add 1 to daysBetween (I needed to do this in my code since I wanted to count the total number of days in the range).

This is somewhat similar to what Daniel suggested , but smaller code, I suppose.

+2
Dec 18 '12 at 15:32
source share

All of these solutions suffer from one of two problems. Either the solution is not absolutely accurate due to rounding errors, leap days and seconds, etc., Or you end the cycle for the number of days between two unknown dates.

This solution solves the first problem and improves the second by about 365 times, better if you know what your maximum range is.

 /** * @param thisDate * @param thatDate * @param maxDays * set to -1 to not set a max * @returns number of days covered between thisDate and thatDate, inclusive, ie, counting both * thisDate and thatDate as an entire day. Will short out if the number of days exceeds * or meets maxDays */ public static int daysCoveredByDates(Date thisDate, Date thatDate, int maxDays) { //Check inputs if (thisDate == null || thatDate == null) { return -1; } //Set calendar objects Calendar startCal = Calendar.getInstance(); Calendar endCal = Calendar.getInstance(); if (thisDate.before(thatDate)) { startCal.setTime(thisDate); endCal.setTime(thatDate); } else { startCal.setTime(thatDate); endCal.setTime(thisDate); } //Get years and dates of our times. int startYear = startCal.get(Calendar.YEAR); int endYear = endCal.get(Calendar.YEAR); int startDay = startCal.get(Calendar.DAY_OF_YEAR); int endDay = endCal.get(Calendar.DAY_OF_YEAR); //Calculate the number of days between dates. Add up each year going by until we catch up to endDate. while (startYear < endYear && maxDays >= 0 && endDay - startDay + 1 < maxDays) { endDay += startCal.getActualMaximum(Calendar.DAY_OF_YEAR); //adds the number of days in the year startDate is currently in ++startYear; startCal.set(Calendar.YEAR, startYear); //reup the year } int days = endDay - startDay + 1; //Honor the maximum, if set if (maxDays >= 0) { days = Math.min(days, maxDays); } return days; } 

If you need days between dates (excluding the last date), just get rid of + 1 when you see endDay - startDay + 1 .

+2
Jan 26 '15 at 20:35
source share

TL; DR

 ChronoUnit.DAYS.between( LocalDate.parse( "1999-12-28" ) , LocalDate.parse( "12/31/1999" , DateTimeFormatter.ofPattern( "MM/dd/yyyy" ) ) ) 

More details

Other answers are out of date. The old date and time classes associated with the earliest versions of Java turned out to be poorly designed, confusing, and complex. Avoid them.

java.time

The Joda-Time project was very successful as a replacement for those old classes. These classes served as inspiration for java.time , which is built into Java 8 and later.

Most of the functionality of java.time is ported to Java 6 and 7 in ThreeTen-Backport and further adapted for Android in ThreeTenABP .

LocalDate

The LocalDate class represents a date value only without time and without a time zone.

Collapsible strings

If your input strings are in the standard ISO 8601 format , the LocalDate class can directly LocalDate string.

 LocalDate start = LocalDate.parse( "1999-12-28" ); 

If not in ISO 8601 format, define a formatting template using DateTimeFormatter .

 String input = "12/31/1999"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM/dd/yyyy" ); LocalDate stop = LocalDate.parse( input , formatter ); 

Elapsed Days Via ChronoUnit

Now get the number of days elapsed between this pair of LocalDate objects. ChronoUnit enum calculates elapsed time.

 long totalDays = ChronoUnit.DAYS.between( start , stop ) ; 

If you are unfamiliar with Java enumerations, you know that they are much more powerful and useful than regular enumerations in most other programming languages. See Enum doc class, Oracle Tutorial and Wikipedia , to learn more.




About java.time

The java.time framework is built into Java 8 and later. These classes supersede the nasty old legacy time classes such as java.util.Date , Calendar and SimpleDateFormat .

The Joda-Time project, now in maintenance mode , we recommend switching to the java.time classes.

To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations. JSR 310 specification .

Where to get java.time classes?

  • Java SE 8 and SE 9 and later
    • Built in.
    • Part of the standard Java API with integrated implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) specifically for Android.
    • See How to use ThreeTenABP ....

The ThreeTen-Extra project extends java.time with additional classes. This project is a proof of possible future additions to java.time. Here you can find useful classes such as Interval , YearWeek , YearQuarter and more .

+2
Jun 27 '16 at 17:25
source share

Another way:

 public static int numberOfDaysBetweenDates(Calendar fromDay, Calendar toDay) { fromDay = calendarStartOfDay(fromDay); toDay = calendarStartOfDay(toDay); long from = fromDay.getTimeInMillis(); long to = toDay.getTimeInMillis(); return (int) TimeUnit.MILLISECONDS.toDays(to - from); } 
+1
Dec 08 '15 at 8:45
source share

I found a very simple way to do this, and this is what I use in my application.

Let's say you have dates in Time objects (or something else, we need milliseconds):

 Time date1 = initializeDate1(); //get the date from somewhere Time date2 = initializeDate2(); //get the date from somewhere long millis1 = date1.toMillis(true); long millis2 = date2.toMillis(true); long difference = millis2 - millis1 ; //now get the days from the difference and that it long days = TimeUnit.MILLISECONDS.toDays(difference); //now you can do something like if(days == 7) { //do whatever when there a week of difference } if(days >= 30) { //do whatever when it been a month or more } 
0
Jun 23 '12 at 18:30
source share

Joda time

The best way is to use Joda-Time , a very successful open source library that you would add to your project.

 String date1 = "2015-11-11"; String date2 = "2013-11-11"; DateTimeFormatter formatter = new DateTimeFormat.forPattern("yyyy-MM-dd"); DateTime d1 = formatter.parseDateTime(date1); DateTime d2 = formatter.parseDateTime(date2); long diffInMillis = d2.getMillis() - d1.getMillis(); Duration duration = new Duration(d1, d2); int days = duration.getStandardDays(); int hours = duration.getStandardHours(); int minutes = duration.getStandardMinutes(); 

If you are using Android Studio , it is very simple to add joda-time. In your build.gradle (app) file:

 dependencies { compile 'joda-time:joda-time:2.4' compile 'joda-time:joda-time:2.4' compile 'joda-time:joda-time:2.2' } 
0
Dec 11 '15 at 21:01
source share
  Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob); Date today = new Date(); long diff = today.getTime() - userDob.getTime(); int numOfDays = (int) (diff / (1000 * 60 * 60 * 24)); int hours = (int) (diff / (1000 * 60 * 60)); int minutes = (int) (diff / (1000 * 60)); int seconds = (int) (diff / (1000)); 
0
Nov 26 '16 at 8:44
source share

use these functions

  public static int getDateDifference(int previousYear, int previousMonthOfYear, int previousDayOfMonth, int nextYear, int nextMonthOfYear, int nextDayOfMonth, int differenceToCount){ // int differenceToCount = can be any of the following // Calendar.MILLISECOND; // Calendar.SECOND; // Calendar.MINUTE; // Calendar.HOUR; // Calendar.DAY_OF_MONTH; // Calendar.MONTH; // Calendar.YEAR; // Calendar.---- Calendar previousDate = Calendar.getInstance(); previousDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth); // month is zero indexed so month should be minus 1 previousDate.set(Calendar.MONTH, previousMonthOfYear); previousDate.set(Calendar.YEAR, previousYear); Calendar nextDate = Calendar.getInstance(); nextDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth); // month is zero indexed so month should be minus 1 nextDate.set(Calendar.MONTH, previousMonthOfYear); nextDate.set(Calendar.YEAR, previousYear); return getDateDifference(previousDate,nextDate,differenceToCount); } public static int getDateDifference(Calendar previousDate,Calendar nextDate,int differenceToCount){ // int differenceToCount = can be any of the following // Calendar.MILLISECOND; // Calendar.SECOND; // Calendar.MINUTE; // Calendar.HOUR; // Calendar.DAY_OF_MONTH; // Calendar.MONTH; // Calendar.YEAR; // Calendar.---- //raise an exception if previous is greater than nextdate. if(previousDate.compareTo(nextDate)>0){ throw new RuntimeException("Previous Date is later than Nextdate"); } int difference=0; while(previousDate.compareTo(nextDate)<=0){ difference++; previousDate.add(differenceToCount,1); } return difference; } 
0
Nov 29 '17 at 6:59
source share



All Articles