将时间戳转换为我们熟悉的字符串类型

需求:提取如下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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值