0

I want to calculate the difference between two dates in days.

I have something like:

String deadline = "2015-08-15";

and I get the current date in:

String timeStamp = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

For example it would be for today:

2015-11-11

How can I calculate the days between these two dates? And what happens if the date is past.

korunos
  • 768
  • 3
  • 11
  • 31

4 Answers4

6

I use this

public String getDateAgo() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    try {
        Date date = sdf.parse(createdAt);
        Date now = new Date(System.currentTimeMillis());
        long days = getDateDiff(date, now, TimeUnit.DAYS);
        if (days < 7)
            return days + "d";
        else
            return days / 7 + "w";
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return "ERROR";
}

private long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
    long diffInMillies = date2.getTime() - date1.getTime();
    return timeUnit.convert(diffInMillies, TimeUnit.MILLISECONDS);
}
Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
2

Use jodatime:

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();
Kristy Welsh
  • 7,828
  • 12
  • 64
  • 106
0

you can use Calendar Class for this. for past time you can pass day, month and year to Calendar Class and after that you can convert it to milisecond. and you can do this for current time. and after that you can convert it to milisecond. then you have 2 value with milisecond unit. and you can calculate their difference and again you can convert this result milisecond to Date. a reading of Calendar class documentation and it's method can be very useful.

karimkhan
  • 321
  • 3
  • 18
0

Try this,

public static long getDatesDifferenceInDays(Date startDate,Date endDate) {
    long different = endDate.getTime() - startDate.getTime();
    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;
    long elapsedDays = different / daysInMilli;
    return elapsedDays;
}
Omar Hassan
  • 727
  • 1
  • 11
  • 24