Vidhyasagar Vasis Vidhyasagar Vasis -4 years ago 68
Java Question

Calculating date difference between two dates in string format

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);

Answer Source

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
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download