筆記

          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 閱讀(1653) 評論(0)  編輯  收藏 所屬分類: jdkwork

          導航

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

          統計

          常用鏈接

          留言簿

          隨筆分類

          隨筆檔案

          收藏夾

          博客

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 平安县| 河东区| 中牟县| 乐都县| 来安县| 阿坝县| 邻水| 阿图什市| 泰来县| 化德县| 南部县| 阿坝县| 绥江县| 旅游| 多伦县| 女性| 拜泉县| 柳林县| 安溪县| 舟山市| 高邮市| 泗水县| 怀宁县| 德兴市| 塔河县| 疏勒县| 犍为县| 无为县| 山西省| 广西| 绥宁县| 葫芦岛市| 濉溪县| 龙井市| 吴江市| 察哈| 南平市| 商南县| 海阳市| 赤壁市| 昆明市|