Java解析时间戳为日期遇ParseException报错,求正确解析方法
解决Java时间戳转日期的ParseException问题
嘿,我一眼就看出问题出在哪了——你用错SimpleDateFormat的方法啦!
为啥会报错?
SimpleDateFormat.parse()这个方法是用来解析符合格式要求的日期字符串的,比如"2018-05-25 10:23:19"这种。但你把时间戳转成字符串"1527217399000"传给它,它完全不知道这是什么格式,自然就抛出ParseException了。
两种正确的解决办法
办法1:用Date构造函数(适合Java 8之前的版本)
Date类本身就支持直接用long类型的时间戳来创建对象,根本不需要转成字符串再去解析。之后再用format()方法把Date转成你想要的日期格式字符串就行:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Long tempTime = 1527217399000L; Date createDate = new Date(tempTime); // 直接用时间戳构造Date对象 System.out.println(format.format(createDate)); // 把Date格式化为字符串输出
这里要分清两个方法的核心区别:
parse():把日期字符串转成Date对象format():把Date对象转成格式化的日期字符串
办法2:用Java 8+的新时间API(强烈推荐)
旧的Date和SimpleDateFormat存在线程不安全的问题,Java 8之后推出的java.time包是更优选择,代码逻辑更清晰也更可靠:
import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; Long tempTime = 1527217399000L; // 将时间戳转为Instant,指定时区(这里用系统默认,也可以手动指定比如ZoneId.of("Asia/Shanghai")) Instant instant = Instant.ofEpochMilli(tempTime); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") .withZone(ZoneId.systemDefault()); String dateStr = formatter.format(instant); System.out.println(dateStr);
另外提一句,你提供的原始数据里有重复的createTime和updateTime字段,这属于JSON格式错误,建议先修正数据结构,不然后续解析数据时还会出问题哦。
内容的提问来源于stack exchange,提问作者Vikki
相关产品推荐
相关产品推荐

