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);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM