這個問題在這里已經有了答案: java DateTimeFormatterBuilder 在測驗時失敗 [重復] (2 個回答) 我如何為 dd MMM yyyy 設定日期格式,如 2020 年 4 月 1 日 [重復] (2 個答案) 4 天前關閉。
我一直在研究一個需要我以這種方式決議字串的專案,我已經分離出了一直拋出錯誤的小部分,
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
public class TestingYearMonth {
public static void main(String[] args) {
YearMonth yearMonth = YearMonth.parse("Feb-17", DateTimeFormatter.ofPattern("MMM-yy"));
System.out.println(yearMonth.getMonth() " " yearMonth.getYear());
}
}
我的老師運行完全相同的代碼,它回傳的輸出沒有問題。但是當我運行它時,我收到以下錯誤
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Feb-17' could not be parsed at index 0
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
at java.base/java.time.YearMonth.parse(YearMonth.java:295)
at com.ethanbradley.assignment6.TestingYearMonth.main(TestingYearMonth.java:10)
我們檢查過,我的 jdk 很好(jdk 11,亞馬遜 coretto 版本)我真的不明白為什么這不起作用,請幫助聰明的互聯網人....
uj5u.com熱心網友回復:
指定一個 Locale
很可能您的 JVM 的默認語言環境不是將“Feb”識別為二月的語言。
指定 aLocale以確定在決議月份名稱時要使用的人類語言和文化規范。
Locale locale = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM-yy" , locale ) ;
YearMonth yearMonth = YearMonth.parse( "Feb-17" , f );
查看此代碼在 IdeOne.com 上實時運行。
ISO 8601
使用本地化文本進行資料交換是不明智的。我建議您向資料發布者介紹用于將日期時間值作為文本交換的ISO 8601標準格式。
年月的標準格式是 YYYY-MM。例子:2017-02。
該java.time類默認使用ISO 8601種格式。
YearMonth.parse( "2017-02" )
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/342541.html
