日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

本文介紹了在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類不強制要求一個線程必須等待,直到另一個線程完成對其內部狀態的修改。使用的三個類是SimpleDateFormatDateFormatFieldPosition

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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,

分享到:
標簽:Java NumberFormatException SimpleDateFormat 代碼 形式 返回
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定