本地时间(北京时间)和“GMT+8”时区时间的区别?

获取本地时间:
String time1 = new SimpleDateFormat("hh:mm:ss").format(new Date());


获取时区“GMT+8”的时间:
String time2 = cal.get(Calendar.HOUR_OF_DAY) + ":" + Calendar.MINUTE + ":" + Calendar.SECOND;


如果“GMT+8”就是北京时间,为什么time1和time2又不相等呢?

下面附上测试代码和测试结果:
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT+8"));
String time1 = new SimpleDateFormat("hh:mm:ss").format(new Date());
String time2 = cal.get(Calendar.HOUR_OF_DAY) + ":" + Calendar.MINUTE + ":" + Calendar.SECOND;
System.out.println("time1=" + time1);
System.out.println("time2=" + time2);

time1=10:54:55
time2=10:12:13


今天查明原因了,上面代码第三行有错误,应该是:
String time2 = cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND);

另外,要求已知时区的时间,应该像下面这样:
public static String getLocalDatetimeString(String local) {
	Calendar cal = new GregorianCalendar(TimeZone.getTimeZone(local));
	cal.setTimeInMillis(Calendar.getInstance().getTimeInMillis());
	String date = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH);
	String time = cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND);
	return date + " " + time;
}

这样调用:
getLocalDatetimeString("GMT+8");




你可能感兴趣的:(java)