转换给定时区的日期/时间 - java
- 论坛
- 转换给定时区的日期/时间 - java
9 浏览
转换给定时区的日期/时间 - java
我想将这个GMT时间戳转换为GMT+13:
2011-10-06 03:35:05
我已经尝试了大约100种不同的DateFormat、TimeZone、Date、GregorianCalendar等组合,试图完成这个非常基本的任务。
这段代码可以对当前时间做到我想要的效果:
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT")); DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z"); formatter.setTimeZone(TimeZone.getTimeZone("GMT+13")); String newZealandTime = formatter.format(calendar.getTime());
但是我想要的是设置时间而不是使用当前时间。
我发现无论何时我尝试像这样设置时间:
calendar.setTime(new Date(1317816735000L));
都会使用本地机器的时区。为什么会这样?我知道当"new Date()"返回UTC+0时间时,那么为什么当你设置毫秒级的时间时它不再假设时间是UTC时间呢?
是否有可能:
- 在一个对象(Calendar/Date/TimeStamp)上设置时间
- (可能)设置初始时间戳的时区(calendar.setTimeZone(...))
- 用新的时区格式化时间戳(formatter.setTimeZone(...))
- 返回一个带有新时区时间的字符串(formatter.format(calendar.getTime()))