本文介紹了在Java代碼中返回SimpleDateFormat形式的NumberFormatException的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我已將SimpleDateFormat對象聲明為常量文件內的靜態字段,如下所示
Constants.Java
public static final SimpleDateFormat GENERAL_TZ_FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
在我的類文件中,我的實現如下所示。
String fDate = getTextValue(empNo, "firstDate");
if (null != fDate && !fDate.isEmpty()) {
try {
Date date = (Date)(Constants.GENERAL_TZ_FORMATTER).parse(fDate);
issue.setDate(date.getTime());
} catch (ParseException e) {
logUtil.error(LOG, e+ "date : " + date);
}
}
錯誤:
Exception while importing data. package name.SecureException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
我的問題是,在某些情況下,這會引發NumberFormatException
(一種非常罕見的情況),所以我一直在想,我做了一個診斷,他們中的大多數人解釋說,這種情況可能是由于SimpleDateFormat不是線程安全的。如果是這種情況,我不清楚這段代碼是如何在不使用多線程的情況下在多線程環境中運行的,它會使DateFormat.parse()的輸入成為空字符串嗎?
Java’s SimpleDateFormat is not thread-safe article
我試過解決這個問題,但真的很難重現這個問題,我想知道你對這個問題的想法,這將幫助我找到更好的解決方案。非常感謝你的建議。
謝謝。
推薦答案
正如您帖子下面的評論已經提到的,您無論如何都不應該使用SimpleDateFormat
。
您可能無意中遇到過SimpleDateFormat
比較麻煩的情況。然而,這并不是唯一的原因。This Stackoverflow post explains why太麻煩了。同一篇帖子中提到的原因之一是SimpleDateFormat
不是線程安全的。線程安全是指當多個進程作用于格式化程序時,即利用格式化程序來格式化日期,并且不會因為干擾而出現不正確、不準確或未定義的結果。
Your link to the article on Callicoder很好地解釋了為什么SimpleDateFormat
造成麻煩。帖子提到了與您收到的相同的異常:
java.lang.NumberFormatException: For input string: ""
簡而言之,線程在使用格式化程序時會發生干擾,因為格式化程序不同步。這意味著SimpleDateFormat
類不強制要求一個線程必須等待,直到另一個線程完成對其內部狀態的修改。使用的三個類是SimpleDateFormat
、DateFormat
和FieldPosition
。
Here’s erroneous code in action。
使用java.time
您需要遷移到java.time
包中提供的更新的Java 8 Date and Time API。由于它們的不變性,它們絕對是線程安全的。在您的情況下,使用java.time.format.DateTimeFormatter
:
public static final DateTimeFormatter GENERAL_TZ_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
ZonedDateTime zdt = ZonedDateTime.parse(fDate, GENERAL_TZ_FORMATTER);
Instant instant = zdt.toInstant();
// Your setDate should really accept an Instant:
issue.setDate(instant);
// If that's REALLY not possible, then you can convert it to an integer
// value equal to the number of milliseconds since 1 January 1970, midnight
//issue.setDate(instant.toEpochMilli());
這篇關于在Java代碼中返回SimpleDateFormat形式的NumberFormatException的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,