Java中ddmmyyyy HH:mm:ss转yyyy-MM-dd HH:mm:ss.SSS出错,求帮助
问题分析与解决
嗨,你遇到的问题核心是日期格式符用错了!在SimpleDateFormat的规则里:
mm代表的是分钟(minutes)MM才是代表月份(months)
你写的输入格式是"ddmmyyyy HH:mm:ss",程序会把字符串里的16当成分钟值,而月份因为没有对应的格式符,被默认设置为1月(Calendar类里月份是0索引,输出显示为Jan),这就导致了日期解析错误。
修正后的代码
把输入格式的mm改成MM就可以解决问题了:
String startDate="06162019 00:00:00"; SimpleDateFormat inSDF = new SimpleDateFormat("ddMMyyyy HH:mm:ss"); SimpleDateFormat outSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); try{ String outDate = ""; Date date = inSDF.parse(startDate); System.out.println(date); outDate = outSDF.format(date); System.out.println(outDate); }catch (final Exception e) { System.out.println(e.getMessage()); }
运行后会得到正确的结果:
Sat Jun 16 00:00:00 GMT 2019
2019-06-16 00:00:00.000
更推荐的方案:使用Java 8+的日期时间API
SimpleDateFormat是线程不安全的,在多线程环境下容易出问题。Java 8及以后推荐使用java.time包下的API,代码更清晰且线程安全:
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateConversion { public static void main(String[] args) { String startDate = "06162019 00:00:00"; DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("ddMMyyyy HH:mm:ss"); DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); LocalDateTime dateTime = LocalDateTime.parse(startDate, inputFormatter); String outDate = dateTime.format(outputFormatter); System.out.println(dateTime); System.out.println(outDate); } }
运行结果同样正确,而且API设计更直观,避免了很多旧API的坑。
内容的提问来源于stack exchange,提问作者Raj Raichand
相关产品推荐
相关产品推荐

