Java中SimpleDateFormat解析非指定格式日期出错求助
解决SimpleDateFormat宽松解析的问题
问题原因
SimpleDateFormat默认处于宽松解析模式,它会自动忽略输入字符串中不符合格式的字符(比如你例子里的横杠),强行尝试解析,因此不会抛出ParseException,反而得到错误的日期结果。
解决方案
调用SimpleDateFormat的setLenient(false)方法开启严格解析模式,当输入字符串与指定格式不匹配时,就会抛出ParseException。
修改后的代码示例
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); dateFormat.setLenient(false); // 开启严格解析模式 try { dateFormat.parse("20000611"); // 格式匹配,正常解析 dateFormat.parse("2000-06-11"); // 格式不匹配,抛出ParseException } catch (ParseException e) { e.printStackTrace(); }
更推荐的方案(Java 8及以上)
如果项目使用Java 8+版本,建议使用java.time包下的新日期时间API,DateTimeFormatter默认就是严格模式,类型更安全,同时避免了SimpleDateFormat的线程不安全问题。
代码示例
import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; public class DateParseDemo { public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); try { LocalDate date1 = LocalDate.parse("20000611", formatter); // 正常解析 LocalDate date2 = LocalDate.parse("2000-06-11", formatter); // 格式不匹配,抛出DateTimeParseException } catch (DateTimeParseException e) { e.printStackTrace(); } } }
内容的提问来源于stack exchange,提问作者Keham Makene
相关产品推荐
相关产品推荐

