Java中String转LocalDateTime失败报错,求解决方案
解决Java中String转LocalDateTime的解析异常问题
嘿,这个坑我踩过!咱们先把问题根源捋清楚:
你用的DateTimeFormatter.ISO_LOCAL_DATE是专门用来解析仅包含日期的字符串(比如你输入的2018-03-03),但LocalDateTime对象要求必须同时具备日期+时间的完整信息——解析器找不到时间部分,自然就抛出DateTimeParseException了。
给你两个针对性的解决方案,按需挑选:
方案一:仅处理日期,用LocalDate代替LocalDateTime
如果你的业务场景只需要日期信息,直接换成LocalDate就搞定了,之后要是真的需要LocalDateTime,再补个默认时间就行:
String date = in.nextLine().trim(); DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE; // 先解析成LocalDate LocalDate localDate = LocalDate.parse(date, formatter); // 转换为LocalDateTime,默认当天0点0分0秒 LocalDateTime dateTime = localDate.atStartOfDay();
方案二:必须得到LocalDateTime,自定义格式化器补全时间默认值
如果业务逻辑一定要LocalDateTime对象,咱们可以给格式化器设置时间部分的默认值,让它自动补全缺失的时间信息:
String date = in.nextLine().trim(); // 构建一个带默认时间的格式化器 DateTimeFormatter formatter = new DateTimeFormatterBuilder() .append(DateTimeFormatter.ISO_LOCAL_DATE) // 解析日期部分 .parseDefaulting(ChronoField.HOUR_OF_DAY, 0) // 默认小时为0 .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0) // 默认分钟为0 .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0) // 默认秒为0 .toFormatter(); LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
另外还有个小提醒:如果你的输入字符串能改成带时间的格式(比如2018-03-03T10:30:00),那直接用DateTimeFormatter.ISO_LOCAL_DATE_TIME解析也是完全可行的~
内容的提问来源于stack exchange,提问作者Mikel Mikel
相关产品推荐
相关产品推荐

