Android Days between two dates

63,841

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);
}
Share:
63,841
Manitoba
Author by

Manitoba

Updated on April 14, 2021

Comments

  • Manitoba
    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
    Manitoba about 10 years
    Hello, thanks bug that won't work if date1 points to the same date as date2
  • Bram
    Bram over 9 years
    Exactly what I was looking for. Thanks! long diff = date2.getTimeInMillis() - date1.getTimeInMillis(); float dayCount = (float) diff / (24 * 60 * 60 * 1000);
  • ePeace
    ePeace over 8 years
    This worked for me after i changed Calendar.HOUR to Calendar.HOUR_OF_DAY
  • Lior Iluz
    Lior Iluz over 8 years
    Joda time library will add 4744 methods to your project. Choose wisely if you want to avoid the 65K methods limit.
  • sud007
    sud007 over 8 years
    Adding jars is really unwise, just for a simple calculation. Be wary of methods limit as @LiorIluz mentioned.
  • statosdotcom
    statosdotcom about 7 years
    But this can be faked if the user manually changes device date... how to workaround it?
  • Tobias Reich
    Tobias Reich almost 7 years
    Ah, just what I was looking for. Thanks!
  • Rodrigo Gontijo
    Rodrigo Gontijo almost 6 years
    This is the best answer !
  • Bogy
    Bogy over 4 years
    You should test your solution before posting it, there is a copy/past error and a typo in Calendar
  • Ole V.V.
    Ole V.V. about 4 years
    One more confusing trait of the poorly designed Calendar class: HOUR does not mean HOUR_OF_DAY. @ePeace
  • 7200rpm
    7200rpm about 4 years
    Update, 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
    gunjot singh almost 4 years
    wooooow !! Thank you :)
  • Ole V.V.
    Ole V.V. almost 4 years
    Using 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 when startDate and endDate have the same time of day.
  • postfixNotation
    postfixNotation almost 4 years
    Hi 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.
    Ole V.V. almost 4 years
    Sorry, 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.
    Ole V.V. almost 4 years
    You may use ChronoUnit.DAYS.between(startDate.toInstant().atZone(ZoneId.‌​systemDefault()).toL‌​ocalDate(), endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDa‌​te()). Feel free to publish in your answer, and I will upvote. You may of course wrap the conversion from Date to LocalDate into an auxiliary method in the same manner as you already do.
  • postfixNotation
    postfixNotation almost 4 years
    Thanks 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
    postfixNotation almost 4 years
    But 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 the instant.atZone(ZoneOffset.UTC) is actually meant as a constant (always UTC). So I was not intending to have this as a variable.
  • postfixNotation
    postfixNotation almost 4 years
    As 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.
    Ole V.V. almost 4 years
    You are correct, a Date is a point in time independent of time zone.
  • Amir Hossein Ghasemi
    Amir Hossein Ghasemi almost 4 years
    it have issue on day light saving timezones
  • Ole V.V.
    Ole V.V. over 3 years
    I am probably repeating myself. (1) the classes Calendar and Date 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
    coding.cat3 about 3 years
    worked like a charm in the way i wanted to , thanks !
  • Izhan Ali
    Izhan Ali almost 3 years
    @statosdotcom set date in your server in unix format and update it daily