2017-04-11 67 views
1

我正在處理一個程序,它告訴文件的上次修改日期是否在日期範圍From和date To中,如果它在範圍內,它將複製但是會出錯轉換上次修改日期時出錯

 File src = new File(sourcefile + File.separator + strErrorFile[i]); 
    if(sourcefile.isDirectory()) 
    { 
     ArrayList<Integer> alDateList = date(strList1); 
     int intDateFrom1 = alDateList.get(0); 
     int intDateTo1 = alDateList.get(1); 
     SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); 
     System.out.println("After Format : " + sdf.format(src.lastModified())); 
    try 
    { 
     lastDate = Integer.parseInt(sdf.format(src.lastModified())); //line 362 
     } catch (NumberFormatException e) { 
      e.printStackTrace(); 
    } 
     if(intDateFrom1 <= lastDate && intDateTo1 >= lastDate) 
    { 
      //copy 
    } 
    } 

錯誤

java.lang.NumberFormatException: For input string: "09/10/2015" 
at java.lang.NumberFormatException.forInputString(Unknown Source) 
at java.lang.Integer.parseInt(Unknown Source) 
at java.lang.Integer.parseInt(Unknown Source) 
at org.eclipse.wb.swt.FortryApplication$4.widgetSelected(FortryApplication.java:362) 
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source) 
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source) 
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source) 
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source) 
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source) 
at org.eclipse.wb.swt.FortryApplication.open(FortryApplication.java:56) 
at org.eclipse.wb.swt.FortryApplication.main(FortryApplication.java:610) 
+2

這不是一個有效的整數 - >「09/10/2015」,您可以做什麼來分割字符串用分隔符「/」,然後連接數組中的每個元素以使數字「091015」。請注意,如果將其轉換爲整數,則前導零將被刪除。 –

+0

@OusmaneMahyDiaw我該如何改變它?對不起,新的 –

+0

看到我的答案進一步的細節。 –

回答

1

java.lang.NumberFormatException:對於輸入字符串: 「2015年9月10日」

這不是一個有效的整數,因此錯誤。您可以採用

一種方法是使用String.replaceAll()方法用空字符串""應主要留給我們09102015取代的/每個實例。

note - 當您將此解析爲整數時,前導零(0)將被刪除。

例子:

String data = sdf.format(src.lastModified()); 

那麼你可以做:

lastDate = Integer.parseInt(data.replaceAll("/","")); 
+0

但我怎麼能沒有StringBuilder呢? –

+1

你可以,但是在for循環中連接字符串「+ =」是一個開銷。 StringBuilder只是一個可變字符串,所以我沒有看到它的問題,無論如何我們將StringBuilder轉換回字符串進行解析。 –

+1

所以,你已經使用了String#replaceAll而不是循環 – MadProgrammer

2

你需要後退一步,看看你需要什麼,你有什麼。

你不想給lastModified值轉換爲String(通過DateFormatter),因爲它不會給你的真正有價值的東西,而不是當你認爲有致力於與日期/時間

工作的整個API

讓我們在看看File#lastModified

的javadoc狀態返回開始:

表示文件的最後修改,以毫秒爲單位SI計測的時間長值如果文件不存在或發生I/O錯誤,則爲0L

好的,這實際上是好的,因爲您可以使用此值生成LocalDateTime對象...

LocalDateTime ldt = LocalDateTime.ofInstant(new Date(src.lastModified()).toInstant(), ZoneId.systemDefault()); 

爲什麼要這樣做?由於LocalDateTime有方法,這使得很容易地比較與其他LocalDateTime對象...

LocalDateTime from = ...; 
    LocalDateTime to = ...; 

    if (ldt.isAfter(from) && ldt.isBefore(to)) { 
     //between... 
    } 

您還可以使用LocalDateTime#equals比較,如果兩個日期都是平等的。

如果您不需要「時間」組件,您可以使用LocalDateTime#toLocalDate獲得一個約會(無時間)基於對象的,但比較過程基本上是一樣的

您可以在this answer看看其中包含用於確定日期/時間值是否在兩個給定日期/時間值之間的總體邏輯