Java:XXX到UTC,然后是UTC到XXX

时间:2015-09-11 12:25:41

标签: java time timezone utc timezone-offset

我创建了一个名为时间的课程,该课程以 UTC 存储时间,但您可以在任何时区传递构造函数时间 ...

public class Time {

  private long timeInUTC;

  // stores given timeInXXX in UTC
  public Time(long timeInXXX, TimeZone tz)
  {
    timeInUTC = timeInXXX - tz.getOffset(timeInXXX); // <---
  }

  public long get()
  {
    return timeInUTC;
  }

  // gets time according to passed timezone
  public long get(TimeZone tz)
  {
    return timeInUTC + tz.getOffset(timeInUTC);
  }

}

现在看到构造函数中的&lt; - ...我不确定这种从UTC时间到达给定时区的方法是否正确...

示例:

long timeUTC = System.currentTimeMillis(); // 1441975581976
// .getRawOffset() is not accurate in this case
// so simply imagine that next line is in fact: long timeCET = 1441971981976;
long timeCET = timeUTC - TimeZone.getTimeZone("CET").getRawOffset(); // 1441971981976

Time t = new Time(timeCET, TimeZone.getTimeZone("CET")); // see constructor definition
System.out.println(t.get()); // expects 1441975581976 (timeUTC)
System.out.println(t.get(TimeZone.getTimeZone("CET"))); // expects 1441971981976 (timeCET)

感谢您的回复...

0 个答案:

没有答案