java西语_使用Java 8 DateTimeFormatter和西班牙语月份名称进行解析
可以刪除對ofLocalizedDateTime()的調用,因為最后你調用ofPattern(),創建另一個格式不同的格式化程序(由ofLocalizedDateTime(FormatStyle.FULL)返回的模式與月份非常不同,所以這是不是你真正想要的).
另一個細節是Mayo是完整的月份名稱,因此模式必須是MMMM(check the javadoc以獲取更多詳細信息).此外,默認情況下,DateTimeFormatter僅接受小寫名稱(至少在我使用西班牙語語言環境進行的測試中),因此您必須將格式化程序設置為不區分大小寫.
您可以使用java.time.format.DateTimeFormatterBuilder來實現:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// case insensitive
.parseCaseInsensitive()
// pattern with full month name (MMMM)
.appendPattern("MMMM yyyy")
// set locale
.toFormatter(new Locale("es", "ES"));
// now it works
fmt.parse("Mayo 2017");
或者,您可以直接將其解析為java.time.YearMonth對象,因為它似乎是這種情況的最佳選擇(因為輸入只有年和月):
YearMonth ym = YearMonth.parse("Mayo 2017", fmt);
System.out.println(ym); // 2017-05
默認值
當輸入沒有所有字段時,SimpleDateFormat只是為它們使用一些默認值.在這種情況下,輸入只有年和月,因此解析的日期將等于解析的月/年,但是日期將設置為1,時間將設置為午夜(在JVM默認時區).
新API對此非常嚴格,除非您告訴它,否則不會創建默認值.配置它的一種方法是使用parseDefaulting和java.time.temporal.ChronoField:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// case insensitive
.parseCaseInsensitive()
// pattern with full month name (MMMM)
.appendPattern("MMMM yyyy")
// default value for day of month
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
// default value for hour
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
// default value for minute
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
// set locale
.toFormatter(new Locale("es", "ES"));
這樣,您可以將其解析為LocalDateTime,并將缺少的字段分配給相應的默認值:
LocalDateTime dt = LocalDateTime.parse("Mayo 2017", fmt);
System.out.println(dt); // 2017-05-01T00:00
如果需要獲取與SimpleDateFormat創建的值相同的java.util.Date,可以將此LocalDateTime轉換為JVM默認時區,然后將其轉換為Date:
Date javaUtilDate = Date.from(dt.atZone(ZoneId.systemDefault()).toInstant());
請注意,我必須明確使用JVM默認時區(ZoneId.systemDefault()),這是SimpleDateFormat所使用的.
另一種方法是手動設置YearMonth值中的值:
// in this case, the formatter doesn't need the default values
YearMonth ym = YearMonth.parse("Mayo 2017", fmt);
ZonedDateTime z = ym
// set day of month to 1
.atDay(1)
// midnight at JVM default timezone
.atStartOfDay(ZoneId.systemDefault());
Date javaUtilDate = date.from(z.toInstant());
API使用IANA timezones names(總是采用Region / City格式,如America / New_York或Europe / Berlin),因此您可以調用ZoneId.of(“America / New_York”).
避免使用3個字母的縮寫(如CST或PST),因為它們是ambiguous and not standard.
您可以通過調用ZoneId.getAvailableZoneIds()獲取可用時區列表(并選擇最適合您系統的時區).
總結
以上是生活随笔為你收集整理的java西语_使用Java 8 DateTimeFormatter和西班牙语月份名称进行解析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDU 2977 Color Squar
- 下一篇: 【TCO2013 Semifinal 2