His*_*His 3 java timezone calendar
我知道还有其他类似的问题,但我想出了自己的方法来获取特定时区的当前时间,所以我只是想确认它是否正确,或者有没有我没有照顾好.
Calendar cal = Calendar.getInstance();
// Assuming we want to get the current time in GMT.
TimeZone tz = TimeZone.getTimeZone("GMT");
cal.setTimeInMillis(calendar.getTimeInMillis()
+ tz.getOffset(calendar.getTimeInMillis())
- TimeZone.getDefault().getOffset(calendar.getTimeInMillis()));
// Calendar should now be in GMT.
Run Code Online (Sandbox Code Playgroud)
以上是否正确?我做了我自己的测试,似乎按预期工作,但只是想与Stack Overflow的专家再次确认.
如果您只Calendar.getInstance使用TimeZone参数执行操作,则日历的get()方法内部状态将返回包含该时区的时间的字段.例如:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
// if i run this at 9 EST this will print 2
System.out.println(cal.get(Calendar.HOUR));
Run Code Online (Sandbox Code Playgroud)
如果您只需要本地时间进行显示,则可以设置TimeZone格式对象.例如:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(new Date()));
Run Code Online (Sandbox Code Playgroud)
就像Macarse所说的那样,如果你需要做更复杂的事情,Joda时间就在这里.Java日期API是一场噩梦.