天天看点

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,如果既有秒的格式,也有毫秒的格式,转换就乱了。目前只能指定一种格式。

总结:

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