2015年11月11日 星期三

[ Java 常見問題 ] How to convert a local date to GMT

Source From Here
Question
The below code doesn't print the date in GMT, but rather prints in the local timezone. How do I get a GMT equivalent date from the current date:
Greenwich Mean Time (GMT) is the mean solar time at the Royal Observatory in Greenwich, London. GMT was formerly used as the international civil time standard, now superseded in that function by Coordinated Universal Time (UTC). Today GMT is considered equivalent to UTC for UK civil purposes (but this is not formalized) and for navigation is considered equivalent to UT1 (the modern form of mean solar time at 0° longitude); these two meanings can differ by up to 0.9 s. Consequently, the term GMT should not be used for precise purposes.

  1. Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));  
  2. java.util.Date fromDate = cal.getTime();  
  3. System.out.println(fromDate);  
How-To
Check below sample code:
  1. package test  
  2.   
  3. private  Date CvtToGmt( Date date ){  
  4.     TimeZone tz = TimeZone.getDefault();  
  5.     Date ret = new Date( date.getTime() - tz.getRawOffset() );  
  6.   
  7.     // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.  
  8.     if ( tz.inDaylightTime( ret )){  
  9.         Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );  
  10.   
  11.         // check to make sure we have not crossed back into standard time  
  12.         // this happens when we are on the cusp of DST (7pm the day before the change for PDT)  
  13.         if ( tz.inDaylightTime( dstDate )){  
  14.             ret = dstDate;  
  15.         }  
  16.     }  
  17.     return ret;  
  18. }  
  19.   
  20. Date fromDate = Calendar.getInstance().getTime();  
  21. System.out.println("UTC Time - "+fromDate);  
  22. System.out.println("GMT Time - "+CvtToGmt(fromDate));  
Sample Output:
UTC Time - Thu Nov 12 09:58:44 CST 2015
GMT Time - Thu Nov 12 01:58:44 CST 2015

 


Supplement
GMT 標準時間 - 全球時區查詢
Wiki - Daylight saving time (DST/日光節約時制)
夏令時間,另譯夏時制(英語:Summer time),又稱日光節約時制、日光節約時間(英語:Daylight saving time),是一種為節約能源而人為規定地方時間的制度,在這一制度實行期間所採用的統一時間稱為「夏令時間」。一般在天亮早的夏季人為將時間提前一小時,可以使人早起早睡,減少照明量,以充分利用光照資源,從而節約照明用電。各個採納夏令時間的國家具體規定不同。


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...