需求:提取如下json中的time转换成我们熟悉的日期格式
{"app_active":{"name":"app_active","json":{"entry":"2","action":"0","error_code":"0"},"time":1595288248066},"attr":{"area":"三门峡","uid":"2F10092A1","app_v":"1.1.0","event_type":"common","device_id":"1FB872-9A1001","os_type":"0.97","channel":"WM","language":"chinese","brand":"xiaomi-3"}}
整体思路:
- 解析json串获取时间戳
- 将字符串转化为long类型
- 定义一个格式化的formatter
- 将长整型转换为Instant类型的对象
- 将instant转换为LocalDateTime
- 调用自定义的formatter格式转成我们想要的格式
代码如下:
// 解析json串获取时间戳
JSONObject jsonObject = JSON.parseObject(jsonStr);
String timestampStr = jsonObject.getJSONObject("app_active").getString("time");
//1.将字符串转化为long类型
long timestamp = Long.parseLong(timestampStr);
//2.定义一个格式化的formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//3.将长整型转换为Instant类型的对象
Instant instant = Instant.ofEpochMilli(timestamp);
//4.将instant转换为LocalDateTime
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
//5.调用自定义的formatter格式转成我们想要的格式
String date = formatter.format(localDateTime);