前言 好久不见,打工人们!
原因 最近遇到一个新需求,需要获得时间戳(单位是秒),然后转成一定得时间格式,yyyyMMddHHmmss ,本以为不就是 Ctr + C 和 Ctr +V 就能搞定,结果碰壁了。
明明输入时当前时间(0202年),结果一转换就变成了 1970XXXX,这个时间差异太离谱了,没见过。
源代码:
public static String getFormatTimestamp() { // 获取当前时间戳,Java8 新特性 long timestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")); //时间戳格式转换 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); return df.format(timestamp); }分析 网上搜索了才知道,原来我获取得时间戳单位是秒,而 SimpleDateFormat 转换的时间戳单位需要毫秒,所以得乘 1000L
df.format(timestamp*1000L);又或者获取时间戳时,直接获取毫秒得时间戳
//获取毫秒数 Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochM修改后源码 方案1
public static String getFormatTimestamp() { // 当前时间戳 long timestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")); //时间戳格式转换 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); return df.format(timestamp*1000L); }方案2
public static String getFormatTimestamp() { // 当前时间戳,获取毫秒数 Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli(); //时间戳格式转换 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); return df.format(timestamp); }参考文献 Java8 LocalDateTime获取时间戳(毫秒/秒)、LocalDateTime与String互转、Date与LocalDateTime互转 关于时间戳转换时间总是1970的问题