-1

For example , Check-in date is 17-3-2019 and check out date is 18-3-2019. So how do I subtract to get their differences?. I'm using Calendar view in java(android studio)

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
  • You need different between two dates? – Ajay Mehta Apr 18 '19 at 05:42
  • Always search Stack Overflow before posting. – Basil Bourque Apr 18 '19 at 06:17
  • FYI, the troublesome date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. Most of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android (<26) in [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Apr 18 '19 at 06:17

1 Answers1

0

You can convert your date ti milliseconds and get difference easily.

Please check this code.

public static long getDiffInDay(String date1, String date2) {
     long diff = dateToMilli("dd-MM-yyyy", date2) - dateToMilli("dd-MM-yyyy", date1);
     return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
 }

public static long dateToMilli(String pattern, String dateTime) {

    final SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.getDefault());

    try {
        return sdf.parse(dateTime).getTime();
    } catch (Exception e) {
        return 0;
    }
}

Call getDiffInDay() method with your CheckIn and CheckOut day. It will return you difference between days.

Like

long Days = getDiffInDay("17-3-2019", "18-3-2019");

Hope it helps.

Ajay Mehta
  • 843
  • 5
  • 14