为什么相同的YearMonth.parse代码仅在我的电脑上解析报错?
问题根因
DateTimeFormatter.ofPattern()方法如果不显式指定Locale,会默认使用JVM启动时继承的操作系统默认Locale- 你的本地操作系统默认Locale为非英语区域(如中文
zh_CN),MMM格式符在这类Locale下匹配的是本地语言的月份缩写(如中文的二月),无法识别英文月份缩写Feb - 你的老师的设备默认Locale为英语区域,所以相同代码可以正常运行
解决方案
创建DateTimeFormatter时显式指定英语Locale即可,修复后的代码如下:
import java.time.YearMonth; import java.time.format.DateTimeFormatter; import java.util.Locale; public class TestingYearMonth { public static void main(String[] args) { // 显式指定英语Locale解析英文月份缩写 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM-yy", Locale.ENGLISH); YearMonth yearMonth = YearMonth.parse("Feb-17", formatter); System.out.println(yearMonth.getMonth() + " " + yearMonth.getYear()); } }
额外建议
所有涉及到自然语言格式的日期、数字解析/格式化场景,都建议显式指定Locale,避免不同设备环境的默认Locale差异导致的兼容性问题。
内容的提问来源于stack exchange,提问作者EthanLTB
相关产品推荐
相关产品推荐

