以字符串格式计算两个日期之间的日期差异

时间:2017-06-13 11:22:36

标签: java

我有两个日期的字符串格式。我需要在几天内得到这两个日期之间的差异。我怎么能得到它?我对这些日期格式很新。请给我任何建议。

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

2 个答案:

答案 0 :(得分:1)

如果您使用的是Java 8,则可以解析the dates to LocalDates而无需格式化程序,因为它们采用ISO格式:

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

然后,您可以使用a ChronoUnit计算它们之间的天数:

long days = ChronoUnit.DAYS.between(start, end);

答案 1 :(得分:0)

见下文

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
    }
}