[英]Error on converting last modified date
我正在研究一個程序,它告訴我們文件的最后一個修改日期是否在日期To和日期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)
您需要退后一步,看看您需要什么以及擁有什么。
您不希望將lastModified
值轉換為String
(通過DateFormatter
),因為它不會為您提供任何真正有價值的東西,而不是當您考慮有一個專用於處理日期/時間的完整API時
讓我們先來看看File#lastModified
JavaDocs聲明它返回:
表示文件上次修改時間的長值,以紀元(1970年1月1日格林威治標准時間00:00:00)為單位,以毫秒為單位,如果文件不存在或發生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
來比較兩個日期是否相等。
如果您不需要“time”組件,可以使用LocalDateTime#toLocalDate
來獲取基於日期(沒有時間)的對象,但比較過程基本相同
您可以查看此答案 ,其中包含用於確定日期/時間值是否在兩個給定日期/時間值之間的總體邏輯
java.lang.NumberFormatException:對於輸入字符串:“09/10/2015”
這不是一個有效的整數,因此是錯誤。
您可以采用的一種方法是使用String.replaceAll()
方法將/
每個實例替換為空字符串""
,這應該基本上留給我們09102015
。
注意 - 當您將其解析為整數時,前導零( 0
)將被刪除。
例:
String data = sdf.format(src.lastModified());
然后你可以這樣做:
lastDate = Integer.parseInt(data.replaceAll("/",""));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.