1、说明
项目中经常遇到时间戳、日期互转的场景,但这里的时间戳通常都是毫秒级别的。由于在开发微信计步时,获取到用户的计步日期为秒级时间戳,需要转换正确的日期格式。如何处理呢?
2、实现方案
方案一:讲秒级时间戳先转换为毫秒级别之后在转换日期
毫秒级时间戳 = 秒级时间戳 * 1000
/** 中国地区常用时间. */
public static final String DATETIME_CONVENTIONAL_CN = "yyyy-MM-dd HH:mm:ss";
public static String timestampToDateStr(Long timestamp,String pattern){
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String sd = sdf.format(new Date(timestamp)); // 时间戳转换日期
System.out.println(sd);
return sd;
}
public static void main(String[] args) {
Long timestamp = 1621440000l*1000; // 秒级* 1000 = 毫秒级
timestampToDateStr(timestamp,DATETIME_CONVENTIONAL_CN);
}
执行结果:
Connected to the target VM, address: '127.0.0.1:63618', transport: 'socket'
2021-05-20 00:00:00
Disconnected from the target VM, address: '127.0.0.1:63618', transport: 'socket'
网友评论