日期解析异常排查:为何该SimpleDateFormat代码无法解析指定日期?
日期解析异常原因及解决办法
问题根源
你的SimpleDateFormat指定的格式dd-MMM-yyyy和待解析的字符串格式完全不匹配:
dd-MMM-yyyy对应日-英文月份缩写-年的结构(例如05-Jan-2024)- 你传入的字符串
sDate = "2024-01-05"是年-数字月-日的结构(yyyy-MM-dd),两者结构对应不上,直接触发解析异常。
解决办法
根据你的需求,分两种场景处理:
场景1:直接解析现有字符串"2024-01-05"
把SimpleDateFormat的格式改为和字符串匹配的yyyy-MM-dd:
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd"); String sDate = "2024-01-05"; Date date1 = dateFormat1.parse(sDate);
场景2:将"2024-01-05"转换为05-Jan-2024格式
需要先按输入格式解析日期,再用目标格式格式化输出:
// 按输入格式解析日期 SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = inputFormat.parse("2024-01-05"); // 按目标格式生成字符串 SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MMM-yyyy"); String targetDateStr = outputFormat.format(date); // 结果为05-Jan-2024
更优方案(Java 8+)
SimpleDateFormat存在线程不安全问题,Java 8及以上版本推荐使用java.time包的日期API:
// 解析输入字符串 DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate localDate = LocalDate.parse("2024-01-05", inputFormatter); // 格式化为目标格式(指定英文Locale避免月份缩写受系统语言影响) DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH); String targetDateStr = localDate.format(outputFormatter); // 结果为05-Jan-2024
内容的提问来源于stack exchange,提问作者user2568374
相关产品推荐
相关产品推荐

