我知道还有其他类似的问题,但我想出了自己的方法来获取特定时区的当前时间,所以我只是想确认它是否正确,或者我有问题没注意。
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.
以上是否正确?我做了自己的测试,它似乎按预期工作,但只是想与 Stack Overflow 中的专家再次确认。
最佳答案
如果您简单地使用 TimeZone 参数执行 Calendar.getInstance
,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));
如果您只需要本地时间用于显示目的,您可以在格式对象上设置 TimeZone
。例如:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(new Date()));
不过就像 Macarse 所说的那样,如果您需要做任何更复杂的事情,Joda 时间就是它所在的位置。 Java 日期 API 是一场噩梦。
关于Java:这是在特定时区将当前时间作为日历对象获取的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1712550/