0

I am trying to find difference in days between two dates. I am using this approach

  Calendar currentTimeCalendar = Calendar.getInstance();
  Calendar postModificationTimeCalendar = Calendar.getInstance();
  postModificationTimeCalendar.setTime(dateeventoccured); //dateeventoccured is in format = Tue Jan 03 00:44:46 EST 2017

  long diffInMillis = currentTimeCalendar.getTimeInMillis() - postModificationTimeCalendar.getTimeInMillis();
  long days = diffInMillis/ (24*60*60*1000);

Now the problem is suppose, I posted something yesterday at 5 pm ,When it is 12 in midnight today difference should be 1 and date should be like yesterday.

but the days remains 0 ,until next day 5 is reached.How to achieve that. I want to show dates as today,yesterday and previous dates.

JJJ
  • 32,902
  • 20
  • 89
  • 102
stack Learner
  • 1,318
  • 3
  • 18
  • 35
  • uhhh, I would suggest you use the LocalDateTime API or if you are on older java versions, Joda Time – Dexter Jan 13 '17 at 06:59
  • Have you considered using [`Java.time.LocalDate`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) or [`org.joda.time.LocalDate`](http://www.joda.org/joda-time/apidocs/org/joda/time/LocalDate.html)? – A.A. Jan 13 '17 at 07:33
  • Possible duplicate of [Get the number of days, weeks, and months, since Epoch in Java](http://stackoverflow.com/questions/6158053/get-the-number-of-days-weeks-and-months-since-epoch-in-java) – AxelH Jan 13 '17 at 10:40

3 Answers3

0

Try this (pass the 2 dates object in this function and you will get the exact diff. in days between 2 dates) :

    public long getDays(Date d1, Date d2) {
        if (d1 != null && d2 != null) {
            long diff = getStartDate(d1).getTimeInMillis() - getStartDate(d2).getTimeInMillis();
            return TimeUnit.MILLISECONDS.toDays(diff);
        } else {
            return -1;
        }
    }

    public Calendar getStartDate(Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal;
    }
Sahil Munjal
  • 463
  • 2
  • 15
0
  private int getDifferenceDay(Date DateStart, Date DateEnd) {
    long diff = DateEnd.getTime() - DateStart.getTime();
    long seconds = diff / 1000;
    int minutes = (int) seconds / 60;
    int hour = minutes / 60;
    int day = hour/24; 
    return day;
}
Umesh AHIR
  • 738
  • 6
  • 20
0

Try using comareTo method it will return the date difference as integer value. private void getDate() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-dd-mm"); String date1="2017-13-01"; String date2="2017-14-01";

Date d1=sdf.parse(date1);
Date d2=sdf.parse(date2);

int compare = d2.compareTo(d1);
Log.e("differece",""+compare);
}