zoukankan      html  css  js  c++  java
  • Java 时区转换(UTC+8 到 UTC 等等)

    前言:需要做时区转换,知道北京为UTC+8,东京为UTC+9,世界标准时间为UTC,所以下面的代码是只需要知道时区是+8还是+9还是0就可以了,不需要使用"CTT"、 "Asia/Shanghai"这种形式。

    java 代码:其实是使用时区 GMT+08:00 这样的格式

    /**
         * 时区转换
         * @param time 时间字符串
         * @param pattern 格式 "yyyy-MM-dd HH:mm"
         * @param nowTimeZone eg:+8,0,+9,-1 等等
         * @param targetTimeZone 同nowTimeZone
         * @return
         */
        public static String timeZoneTransfer(String time, String pattern, String nowTimeZone, String targetTimeZone) {
            if(StringUtils.isBlank(time)){
                return "";
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT" + nowTimeZone));
            Date date;
            try {
                date = simpleDateFormat.parse(time);
            } catch (ParseException e) {
                logger.error("时间转换出错。", e);
                return "";
            }
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT" + targetTimeZone));
            return simpleDateFormat.format(date);
        }

    单测代码:

    @Test
        public void testTimeZoneTransfer(){
            String result = DateUtil.timeZoneTransfer("2018-07-03 15:43", "yyyy-MM-dd HH:mm", "+8", "0");
            Assert.assertEquals("转换错误", "2018-07-03 07:43", result);
    
            result = DateUtil.timeZoneTransfer("2018-07-03 15:43", "yyyy-MM-dd HH:mm", "+9", "0");
            Assert.assertEquals("转换错误", "2018-07-03 06:43", result);
    
            result = DateUtil.timeZoneTransfer("2018-07-03 15:43", "yyyy-MM-dd HH:mm", "-1", "0");
            Assert.assertEquals("转换错误", "2018-07-03 16:43", result);
    
            result = DateUtil.timeZoneTransfer("2018-07-03 15:43", "yyyy-MM-dd HH:mm", "+8", "+9");
            Assert.assertEquals("转换错误", "2018-07-03 16:43", result);
    
            result = DateUtil.timeZoneTransfer("2018-07-03 15:43", "yyyy-MM-dd HH:mm", "+0", "+8");
            Assert.assertEquals("转换错误", "2018-07-03 23:43", result);
    
            result = DateUtil.timeZoneTransfer("2018-07-03 15:43", "yyyy-MM-dd HH:mm", "+0", "0");
            Assert.assertEquals("转换错误", "2018-07-03 15:43", result);
        }
  • 相关阅读:
    JSON
    Chromium 修改chrome.exe
    Chromium 修改任务管理器显示的Chromium
    winhttp get请求https
    string wstring 互转
    浏览器指纹在线监测获取网址
    咕了的构造题单总结
    Git 常用命令总结
    C# 网络地址是否有效
    IDEA如何从断点里获取对象所有数据
  • 原文地址:https://www.cnblogs.com/yuxiaole/p/9259221.html
Copyright © 2011-2022 走看看