-1

I have two dates in string format.I need to get the difference between these two dates in days.How can I get it?I am very new to these date format.please give me any suggestion.

2017-06-13
2017-06-27

    String newDate = null;
    Date dtDob = new Date(GoalSelectionToDate);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    newDate = sdf.format(dtDob);

    String newDate1 = null;
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    newDate1 = sdf1.format(currentDate);
    System.out.println("currentdateformat"+newDate1);
    System.out.println("anotherdateformat"+newDate);
  • Does this help - https://stackoverflow.com/questions/13732577/convert-string-to-date-to-calculate-the-difference – Sripriya V Jun 13 '17 at 11:27
  • 3
    Possible duplicate of [Convert String to date to calculate the difference](https://stackoverflow.com/questions/13732577/convert-string-to-date-to-calculate-the-difference) – Tom Jun 13 '17 at 11:30

2 Answers2

1

see below

import java.time.LocalDate;
import java.time.Period;

public class DatesComparison {

    public static void main(String[] args) {
        String date1= "2017-06-13";
        String date2= "2017-06-27";




        LocalDate localDate1 = LocalDate.parse(date1);
        LocalDate localDate2 = LocalDate.parse(date2);

        Period intervalPeriod = Period.between(localDate1, localDate2);

        System.out.println("Difference of days: " + intervalPeriod.getDays());  // Difference of days: 14
        System.out.println("Difference of months: " + intervalPeriod.getMonths());  // Difference of months: 0
        System.out.println("Difference of years: " + intervalPeriod.getYears());  // Difference of years: 0
    }
}
Jose Zevallos
  • 685
  • 4
  • 3
  • 2
    "see below" is not a helpful answer explanation. – Tom Jun 13 '17 at 11:29
  • 3
    @JoseZevallos You don't really answer the question - in particular, if the difference is more than one month, `getDays` will not return the number of days between the two dates. – assylias Jun 13 '17 at 11:33
1

If you are using Java 8, you can parse the dates to LocalDates without the need for a formatter because they are in ISO format:

LocalDate start = LocalDate.parse("2017-06-13");
LocalDate end = LocalDate.parse("2017-06-27");

Then you can calculate the number of days between them with using a ChronoUnit:

long days = ChronoUnit.DAYS.between(start, end);
assylias
  • 321,522
  • 82
  • 660
  • 783