UTC時間:通用協調時(Universal Time Coordinated),與格林尼治平均時(GMT,Greenwich Mean Time)一樣,都是與英國倫敦的本地時相同。
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class GetUTCTime { // 取得本地時間: private Calendar cal = Calendar.getInstance(); // 取得時間偏移量: private int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET); // 取得夏令時差: private int dstOffset = cal.get(java.util.Calendar.DST_OFFSET); public static void main(String[] args) { GetUTCTime gc = new GetUTCTime(); long mill = gc.getUTCTimeStr(); gc.setUTCTime(mill); } public long getUTCTimeStr() { System.out.println("local millis = " + cal.getTimeInMillis()); // 等效System.currentTimeMillis() , 統一值,不分時區 // 從本地時間里扣除這些差量,即可以取得UTC時間: cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset)); long mills = cal.getTimeInMillis(); System.out.println("UTC = " + mills); return mills; } public void setUTCTime(long millis) { cal.setTimeInMillis(millis); SimpleDateFormat foo = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = foo.format(cal.getTime()); System.out.println("GMT time= " + time); // 從本地時間里扣除這些差量,即可以取得UTC時間: cal.add(java.util.Calendar.MILLISECOND, (zoneOffset + dstOffset)); time = foo.format(cal.getTime()); System.out.println("Local time = " + time); } public void getGMTTime() { //mothed 2 TimeZone gmtTime = TimeZone.getTimeZone("GMT"); Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); format.setTimeZone(gmtTime); System.out.println("GMT Time: " + format.format(date)); //method 2 Calendar calendar1 = Calendar.getInstance(); calendar1.setTimeZone(gmtTime); //System.out.println(calendar1.getTime()); //時區無效 //System.out.println(calendar1.getTimeInMillis()); //時區無效 System.out.println("GMT hour = " + calendar1.get(Calendar.HOUR)); } }
