1 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊
正如 javadoc ofDateTimeFormatter解釋的那樣,我引用:正好 4 個(gè)模式字母將使用完整的形式。正好 5 個(gè)模式字母將使用窄格式。
我也不知道為什么;狹窄的形式實(shí)際上非常非常短,大概幾個(gè)月它會(huì)是第一個(gè)字母,這是非常沒(méi)用的,例如 6 月和 7 月都以 J 開(kāi)頭(即使是德語(yǔ))。弄清楚這種事情的最簡(jiǎn)單方法是反過(guò)來(lái):取一個(gè)已知日期并使用.format而不是.parse查看它的樣子。
你想要的是 4x 字母 M,這是月份的完整名稱。
正如一些評(píng)論所說(shuō),它的確切運(yùn)作方式將取決于您的系統(tǒng)區(qū)域設(shè)置,這使得測(cè)試和建議比它需要的要困難得多。通常,您應(yīng)該始終明確選擇語(yǔ)言環(huán)境。您可以調(diào)用該withLocale方法來(lái)強(qiáng)制它。
這是一些示例代碼:
import java.time.*; import java.time.format.*; import java.util.*;
public class Test {
public static void main(String[] args) {
String myFormatNarrow = "dd MMMMM uuuu";
String myFormatFull = "dd MMMM uuuu";
String dateToFormat = "26 Juni 2010";
String dateToFormat2 = "26 J 2010";
String dateToFormat3 = "26 Jun 2010";
DateTimeFormatter myFormatter;
LocalDate myDate;
myFormatter = new DateTimeFormatterBuilder().appendPattern(myFormatFull)
.toFormatter().withResolverStyle(ResolverStyle.STRICT).withLocale(Locale.GERMAN);
System.out.println("FULL: " + myFormatter.format(LocalDate.of(2010, 6, 26)));
myDate = LocalDate.parse(dateToFormat, myFormatter);
System.out.println("PARSED: " + myDate);
myFormatter = new DateTimeFormatterBuilder().appendPattern(myFormatNarrow)
.toFormatter().withResolverStyle(ResolverStyle.STRICT).withLocale(Locale.GERMAN);
System.out.println("NARROW: " + myFormatter.format(LocalDate.of(2010, 6, 26)));
myDate = LocalDate.parse(dateToFormat2, myFormatter);
// It parses a single J as 'july'. Clearly showing why narrow-form is useless here.
System.out.println("PARSED: " + myDate);
// note that even ResolverStyle.LENIENT can't do it either; this will fail:
myFormatter = myFormatter.withResolverStyle(ResolverStyle.LENIENT);
// myDate = LocalDate.parse(dateToFormat3, myFormatter);
// System.out.println("PARSED: " + myDate);
}
}
添加回答
舉報(bào)