时间工具类之“LocalDateTime方案转换地域性时差问题->UTC时间转本地时间”

一.使用方案

UTC时间:yyyy-MM-dd'T'HH:mm:ss.SSS'Z'  -》  2023-11-23T00:58:01.627Z

本地时间:LocalDateTime.toString() -> 2023-11-23T08:58:01.627

二.代码

// 获取本地时间的时区 -》ZoneId.systemDefault();
// 将字符串解析为Instant对象 -> Instant.parse("2022-01-01T00:00:00Z")
// 转换为LocalDateTime对象LocalDateTime.ofInstant(将字符串解析为Instant对象,获取本地时间的时区);
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.parse("2023-11-23T00:58:01.627Z"), ZoneId.systemDefault());
System.out.println("localDateTime = " + localDateTime);

 

三.结果

localDateTime = 2023-11-23T08:58:01.627

 

四.扩展-》自定义工具类方案

utcTime-》UTC时间 -》 2023-11-23T00:58:01.627Z
utcTimePatten -》 美国时间格式 -》 yyyy-MM-dd'T'HH:mm:ss.SSS'Z' 
localTimePatten -》 转换后的格式 -》yyyy-MM-dd HH:mm:ss
使用方案
String s1 = Utc.utc2Local(loanTime, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "yyyy-MM-dd HH:mm:ss");
工具类
    public static String utc2Local(String utcTime, String utcTimePatten, String localTimePatten)
    {
        SimpleDateFormat utcFormater = new SimpleDateFormat(utcTimePatten);
        utcFormater.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date gpsUTCDate = null;
        try
        {
            gpsUTCDate = utcFormater.parse(utcTime);
        }
        catch (ParseException e)
        {
            return utcTime;
        }
        SimpleDateFormat localFormater = new SimpleDateFormat(localTimePatten);
        localFormater.setTimeZone(TimeZone.getDefault());
        String localTime = localFormater.format(gpsUTCDate.getTime());
        return localTime;
    }

 

posted @ 2023-11-23 20:29  骚哥  阅读(120)  评论(0编辑  收藏  举报