2017-06-13 156 views
-1

我有两个字符串格式的日期。我需要在几天内得到这两个日期之间的差异。我如何得到它?我对这些日期format.please新非常新我有任何建议。以字符串格式计算两个日期之间的日期差异

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

这是否有帮助 - https://stackoverflow.com/questions/13732577/convert-string-to-date-to-calculate-the-difference –

+3

可能的重复[转换字符串到日期以计算差异](https: //sackoverflow.com/questions/13732577/convert-string-to-date-to-calculate-the-difference) – Tom

回答

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

“see below”不是一个有用的答案解释。 – Tom

+0

代码是不言自明的 –

+3

@JoseZevallos你并没有真正回答这个问题 - 特别是如果差异超过一个月,'getDays'将不会返回这两个日期之间的天数。 – assylias

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); 
相关问题