2017-06-13 153 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); 
相關問題