-1

I have a two dates that are of string type. How do I count how many days there are not considering milliseconds?

This code gives me the number of milliseconds between the dates:

    try {
        SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
        String inputString1 = 23-11-2018;
        String inputString2 = 24-11-2018;
        Date date1 = myFormat.parse(inputString1);
        Date date2 = myFormat.parse(inputString2);
        diff = date2.getTime() - date1.getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
Masum
  • 1,037
  • 15
  • 32
  • 1
    please post the inputted text in inputString1, inputString2 – Gourango Sutradhar Nov 26 '18 at 04:47
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Nov 26 '18 at 07:29
  • You are correct in not wanting to convert from milliseconds. Doing so would occasionally give incorrect results since a day may be for example 23, 24 or 25 hours. – Ole V.V. Nov 26 '18 at 11:40

2 Answers2

1

Try this...

SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
String inputString1 = "2017-04-01";
String inputString2 = "2018-04-01";

try {
    Date date1 = myFormat.parse(inputString1);
    Date date2 = myFormat.parse(inputString2);
    long diff = date2.getTime() - date1.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}

If you don't want to use millisecond than you have to use Joda Time , which is a much better API. Then you can use:

int days = Days.daysBetween(date1, date2).getDays();
Alireza Noorali
  • 3,129
  • 2
  • 33
  • 80
Ravindra Kumar
  • 1,842
  • 14
  • 23
0

You can calculate the number of days by doing

int days = (int) (diff / (1000*60*60*24));
TransmissionsDev
  • 388
  • 4
  • 16