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:
How-To
Check below sample code:
Sample Output:
Supplement
* GMT 標準時間 - 全球時區查詢
* Wiki - Daylight saving time (DST/日光節約時制)
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:
- Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
- java.util.Date fromDate = cal.getTime();
- System.out.println(fromDate);
Check below sample code:
- package test
- private Date CvtToGmt( Date date ){
- TimeZone tz = TimeZone.getDefault();
- Date ret = new Date( date.getTime() - tz.getRawOffset() );
- // if we are now in DST, back off by the delta. Note that we are checking the GMT date, this is the KEY.
- if ( tz.inDaylightTime( ret )){
- Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );
- // check to make sure we have not crossed back into standard time
- // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
- if ( tz.inDaylightTime( dstDate )){
- ret = dstDate;
- }
- }
- return ret;
- }
- Date fromDate = Calendar.getInstance().getTime();
- System.out.println("UTC Time - "+fromDate);
- System.out.println("GMT Time - "+CvtToGmt(fromDate));
Supplement
* GMT 標準時間 - 全球時區查詢
* Wiki - Daylight saving time (DST/日光節約時制)
沒有留言:
張貼留言