我需要更改日历时区偏移量
我尝试了很多事情;
1-
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(TimeUnit.HOURS.convert(rawOffset, TimeUnit.MILLISECONDS) +
System.currentTimeMillis());
2-
TimeZone timezone = new SimpleTimeZone();
timezone.setRawOffset(rawOffset);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(timezone);
我们的API返回+1.0时区(柏林),但我无法更改日历时区偏移量。怎么改变?
答案 0 :(得分:1)
不要混入原始偏移量。 Java比您更了解柏林的偏移量。并考虑不使用Calendar
。该类存在许多设计问题,被认为已经过时。
ZonedDateTime zdtBerlin = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
System.out.println("Zeit in Berlin: " + zdtBerlin);
当我刚刚运行此代码段时,我得到了以下输出:
柏林的Zeit:2019-02-08T19:23:00.275 + 01:00 [欧洲/柏林]
顾名思义,ZonedDateTime
中包含一个时区。在这种情况下,欧洲/柏林。它是GregorianCalendar
(抽象Calendar
类的最常见的具体子类)的现代替代品。
是的,java.time在较新和较旧的Android设备上均可正常运行。它只需要至少 Java 6 。
org.threeten.bp
导入日期和时间类。代码段1:您将Calendar
的时间设置为未来一个小时。您尚未设置时区。
代码段2:第一个SimpleTimeZone
没有无参数构造函数,因此new SimpleTimeZone()
无法正常工作。接下来,其setRawOffset
期望以毫秒为单位的偏移量。如果rawOffset
为1,则将偏移量设置为1毫秒。
java.time
。java.time
。java.time
向Java 6和7(JSR-310的ThreeTen)的反向端口。