首頁 > Java > java教程 > 主體

如何避免Java中日期字串解析異常?

DDD
發布: 2024-11-13 16:25:03
原創
492 人瀏覽過

How to Avoid Date String Parsing Exceptions in Java?

Solving Date String Parsing Exceptions with Java

Parsing date strings into Date objects is a common task in Java programming. However, incorrect patterns can lead to exceptions.

Consider the following example:

String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("E MM dd kk:mm:ss z yyyy");
Date result = df.parse(target);
登入後複製

This code throws a java.text.ParseException due to an incorrect pattern. To resolve this issue, the pattern needs to be modified.

In this specific case, the abbreviations for the day (EEE) and month (MMM) should be used instead of the more compact forms (E and MM). Additionally, the pattern should explicitly specify the locale as English. This is because the default locale may not be English on all platforms.

Here's the corrected code:

String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
Date result = df.parse(target);
登入後複製

This updated code successfully parses the date string and produces the correct Date object:

Thu Sep 28 07:29:30 BOT 2000
登入後複製

It's important to use the correct pattern and specify the locale to avoid exceptions when parsing date strings.

以上是如何避免Java中日期字串解析異常?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板