java時區轉化相關工具方法


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

public class Test
{
   
    public static void main(String[] args)
    {
        System.out.println("默認時區:" + getLocalTimeId());
        System.out.println("時區列表:" + getZoneList());
       
        //原時區的時間
        String sourceTime = "2013-08-06 15:30:00";
        //原時區東八區Asia/Shanghai,GMT+8:00
        String sourceId = "Asia/Shanghai";
        //目標時區Asia/Dili,GMT+09:00
        String targetId = "Asia/Dili";
        //轉換后的時間
        String targetTime = timeConvert(sourceTime, sourceId, targetId);
        System.out.println("原來為:" + sourceTime);
        System.out.println("轉換為:" + targetTime);
       
    }
   
    /**
     * 獲取本地默認時區id
     * @return string 本地時區id
     */
    public static String getLocalTimeId()
    {
        TimeZone defaultTimeZone = TimeZone.getDefault();
        String sourceId = defaultTimeZone.getID();
        return sourceId;
    }
   
    /**
     * 獲取受支持的所有可用 ID
     * 用來作為頁面顯示的時區下拉列表
     * 以絕對時區顯示(不考慮夏令時)
     * @return map 存儲時區列表+偏移量的map(可用來顯示如Hongkong,GMT+08:00)
     * 實際使用時,傳給服務器是零時區,值傳遞時區id就可以了,不傳遞偏移量
     */
    public static Map<String, String> getZoneList()
    {
        String[] zoneIds = TimeZone.getAvailableIDs();
        int length = zoneIds.length;
        TimeZone timeZone = null;
        //存儲時區列表+偏移量到map中
        Map<String, String> map = new HashMap<String, String>(650);
        long offset = 0L;
        String diplayOffset = "";
        for (int i = 0; i < length; i++)
        {
            //獲取給定 ID 的 TimeZone
            timeZone = TimeZone.getTimeZone(zoneIds[i]);
            //返回添加到 UTC 以獲取此時區中的標准時間的時間偏移量(以毫秒為單位)。
            offset = timeZone.getRawOffset();
            //對偏移量做顯示,如GMT-09:30、GMT+09:30
            diplayOffset = appendZoneSuffix(offset);
            //存儲到map中,形式為Hongkong---GMT+08:00
            map.put(zoneIds[i], diplayOffset);
        }
        return map;
    }
   
    /**
     * 添加時區偏移量
     * @param offset 偏移量(以毫秒為單位)
     * @return 日期
     */
    public static String appendZoneSuffix(long offset)
    {
        //將偏移量轉化為小時(小數去除不要)
        long hour = Long.valueOf((offset / 3600000));
        //偏移量對小時取余數,得到小數(以毫秒為單位)
        double decimals = offset % 3600000;
        //顯示為09:30分鍾形式
        double decimalsZone = (decimals / 3600000) * 60 / 100;
        String sAdd = "";
        if (hour >= 0)
        {
            sAdd = "+";
        }
        else
        {
            sAdd = "-";
        }
        hour = hour > 0 ? hour : -hour;
        String sHour = hour + "";
        if (sHour.length() == 1)
        {
            sHour = '0' + sHour;
        }
       
        decimalsZone = decimalsZone < 0 ? -decimalsZone : decimalsZone;
        String sDecimalsZone = decimalsZone + "";
        sDecimalsZone = sDecimalsZone.substring(2);
        if (sDecimalsZone.length() == 1)
        {
            sDecimalsZone = sDecimalsZone + '0';
        }
        else if (sDecimalsZone.length() >= 3)
        {
            sDecimalsZone = sDecimalsZone.substring(0, 2);
        }
        return "GMT" + sAdd + sHour + ':' + sDecimalsZone;
    }
   
    /**
     * 時區 時間轉換方法:將當前時間(可能為其他時區)轉化成目標時區對應的時間
     * @param sourceTime 時間格式必須為:yyyy-MM-dd HH:mm:ss
     * @param sourceId 入參的時間的時區id
     * @param targetId 要轉換成目標時區id(一般是是零時區:取值UTC)
     * @return string 轉化時區后的時間
     */
    public static String timeConvert(String sourceTime, String sourceId,
            String targetId)
    {
        //校驗入參是否合法
        if (null == sourceId || "".equals(sourceId) || null == targetId
                || "".equals(targetId) || null == sourceTime
                || "".equals(sourceTime))
        {
            return "";
        }
        //校驗 時間格式必須為:yyyy-MM-dd HH:mm:ss
        String reg = "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$";
        if (!sourceTime.matches(reg))
        {
            return "";
        }
       
        try
        {
            //時間格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //根據入參原時區id,獲取對應的timezone對象
            TimeZone sourceTimeZone = TimeZone.getTimeZone(sourceId);
            //設置SimpleDateFormat時區為原時區(否則是本地默認時區),目的:用來將字符串sourceTime轉化成原時區對應的date對象
            df.setTimeZone(sourceTimeZone);
            //將字符串sourceTime轉化成原時區對應的date對象
            Date sourceDate = df.parse(sourceTime);
           
            //開始轉化時區:根據目標時區id設置目標TimeZone
            TimeZone targetTimeZone = TimeZone.getTimeZone(targetId);
            //設置SimpleDateFormat時區為目標時區(否則是本地默認時區),目的:用來將字符串sourceTime轉化成目標時區對應的date對象
            df.setTimeZone(targetTimeZone);
            //得到目標時間字符串
            String targetTime = df.format(sourceDate);
            return targetTime;
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        return "";
       
    }
}


免責聲明!

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



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