筆記

          way

          Java時區處理

          通用協調時(UTC, Universal Time Coordinated),格林尼治平均時(GMT, Greenwich Mean Time) 由于歷史原因,這兩個時間是一樣的。
          北京時區是東八區,領先UTC八個小時,在電子郵件信頭的Date域記為+0800。
          轉換中,最重要的公式就是:
          UTC + 時區差 = 本地時間
              public static Calendar convertToGmt(Calendar cal) {
                  Date date 
          = cal.getTime();
                  TimeZone tz 
          = cal.getTimeZone();

                  System.out.println(
          "input calendar has date [" + date + "]");

                  
          // Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
                  long msFromEpochGmt = date.getTime();

                  
          // gives you the current offset in ms from GMT at the current date
                  int offsetFromUTC = tz.getOffset(msFromEpochGmt);
                  System.out.println(
          "offset is " + offsetFromUTC);

                  
          // create a new calendar in GMT timezone, set to this date and add the offset     
                  Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
                  Calendar utcCal 
          = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

                  gmtCal.setTime(date);
                  //根據東西時區,選擇offsetFromUTC為正或負數
                  gmtCal.add(Calendar.MILLISECOND, offsetFromUTC);

                  utcCal.setTime(date);
                  utcCal.add(Calendar.MILLISECOND, offsetFromUTC);

                  System.out.println(
          "Created GMT cal with date [" + gmtCal.getTime()
                          
          + "==" + utcCal.getTime() + "]");
                  
          return gmtCal;
              }

          posted on 2012-03-15 23:08 yuxh 閱讀(1652) 評論(0)  編輯  收藏 所屬分類: jdkwork

          導航

          <2012年3月>
          26272829123
          45678910
          11121314151617
          18192021222324
          25262728293031
          1234567

          統計

          常用鏈接

          留言簿

          隨筆分類

          隨筆檔案

          收藏夾

          博客

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 务川| 安岳县| 南召县| 建宁县| 武穴市| 竹山县| 汝城县| 鄂尔多斯市| 常德市| 新泰市| 渑池县| 安仁县| 左贡县| 建宁县| 永修县| 龙州县| 赤壁市| 兴国县| 称多县| 兴仁县| 磐石市| 富宁县| 绥芬河市| 仙居县| 九台市| 肇州县| 罗山县| 顺昌县| 大姚县| 厦门市| 清水河县| 信丰县| 义乌市| 轮台县| 桑日县| 伊金霍洛旗| 乌苏市| 海安县| 黄龙县| 嵩明县| 天气|