1616583225000时间戳(chuo)转换为指定日期格式

编程入门 行业动态 更新时间:2024-10-08 02:25:36

1616583225000时间戳(chuo)<a href=https://www.elefans.com/category/jswz/34/1771419.html style=转换为指定日期格式"/>

1616583225000时间戳(chuo)转换为指定日期格式

时间戳(chuo)转换为指定日期格式

 

unix时间戳是从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒

UNIX时间戳的0按照ISO 8601规范为 :1970-01-01T00:00:00Z.

一个小时表示为UNIX时间戳格式为:3600秒;一天表示为UNIX时间戳为86400秒,闰秒不计算。

比如:

2021-03-25 15:55:55  转换为时间戳(秒): 1616658955

2021-03-25 15:55:55  转换为时间戳(毫秒):1616658955000

只有两个单位毫秒

 

要求

了解了UCT时间的处理,加上时间戳呢?

将数组中数值是字符串的时间戳时间(毫秒的格式)和UTC时间转换为常见的日期格式

    [dream, 160635522322,  1616228935000, yan]

变成:

   [dream, 2020-11-26 09:47:03, 2021-03-20 16:28:55, yan]

 

处理:

思路:

1,先判断是否为日期格式

2,然后把时间戳日期格式的内容转换为常见的格式

 

代码:

private static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";public static void main(String[] args) {List<String> strList = Lists.newArrayList("dream","56","1606355223","1606355223232", "1616228935000","yan");System.out.println("======= change later===========");System.out.println(strList.toString());List<String> changeList = ListUtils.emptyIfNull(strList).stream().map(e -> {if(isValidTimeStamp(e)){return formatTimeStamp(e);}return e;}).collect(Collectors.toList());System.out.println("======= change later===========");System.out.println(changeList.toString());}public static boolean isValidTimeStamp(String timestamp) {SimpleDateFormat df = new SimpleDateFormat(TIME_FORMAT);try {df.format(new Date(Long.parseLong(String.valueOf(timestamp))));return true;} catch (Exception e) {return false;}}public static String formatTimeStamp(String timestamp) {// Instant.ofEpochMilli 转 毫秒,  Instant.ofEpochSecond 转 秒LocalDateTime localDateTime = Instant.ofEpochMilli(Long.parseLong(timestamp)).atZone(ZoneId.systemDefault()).toLocalDateTime();return localDateTime.format(DateTimeFormatter.ofPattern(TIME_FORMAT));}public static String formatTimeStamp2(String timeStamp) {SimpleDateFormat sdf=new SimpleDateFormat(TIME_FORMAT);return sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));}

结果:

======= change later===========
[dream, 56, 1606355223, 1606355223232, 1616228935000, yan]
======= change later===========
[dream, 1970-01-01 08:00:00, 1970-01-19 22:12:35, 2020-11-26 09:47:03, 2021-03-20 16:28:55, yan]

处理时间戳的时候,会有两个问题:

   1,会把数值类型的也转换了,把56 变成了1970-01-01 08:00:00,可以根据实际情况,限制下长度

   2,如果既有秒的格式,也有毫秒的格式,转换就乱了。目前只能指定一种格式

 

总结:

   时间戳格式的处理,判断是时候,还是根据是否可以日期格式化进行判断。其它暂时也没有想到好的方式去判断。处理的时候,要指定毫秒的格式还是秒的格式。因为时间戳是动态不断化,不断累加,所以不好判断。实际中更多是指定字段指定格式,所以好处理。混合在一起就不好弄了。

 

更多推荐

1616583225000时间戳(chuo)转换为指定日期格式

本文发布于:2024-02-19 16:35:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1764930.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   日期   格式   时间   chuo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!