【发布时间】:2012-07-22 17:11:21
【问题描述】:
我想用 Joda 时间将当前时间转换为特定时区的时间。
有没有办法将DateTime time = new DateTime() 转换为特定时区,或者获取time.getZone() 和另一个DateTimeZone 之间的小时数差异,然后执行time.minusHours 或time.plusHours?
【问题讨论】:
标签: java datetime timezone jodatime
我想用 Joda 时间将当前时间转换为特定时区的时间。
有没有办法将DateTime time = new DateTime() 转换为特定时区,或者获取time.getZone() 和另一个DateTimeZone 之间的小时数差异,然后执行time.minusHours 或time.plusHours?
【问题讨论】:
标签: java datetime timezone jodatime
我想用 Joda 时间将当前时间转换为特定时区的时间。
不清楚您是否已经得到当前时间。如果你已经得到它,你可以使用withZone:
DateTime zoned = original.withZone(zone);
如果您只是获取当前时间,请使用appropriate constructor:
DateTime zoned = new DateTime(zone);
或使用DateTime.now:
DateTime zoned = DateTime.now(zone);
【讨论】:
DateTime.now(zone)吗?
DateTime dt = new DateTime();
// translate to London local time
DateTime dtLondon = dt.withZone(DateTimeZone.forID("Europe/London"));
间隔:
Interval interval = new Interval(start, end); //start and end are two DateTimes
【讨论】:
java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,改用modern Date-Time API*。
另外,下面引用的是来自home page of Joda-Time的通知:
请注意,从 Java SE 8 开始,用户被要求迁移到 java.time (JSR-310) - JDK 的核心部分,它取代了这个项目。
使用现代日期时间 API java.time 的解决方案:
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
// ZonedDateTime.now() is same as ZonedDateTime.now(ZoneId.systemDefault()). In
// order to specify a specific timezone, use ZoneId.of(...) e.g.
// ZonedDateTime.now(ZoneId.of("Europe/London"));
ZonedDateTime zdtDefaultTz = ZonedDateTime.now();
System.out.println(zdtDefaultTz);
// Convert zdtDefaultTz to a ZonedDateTime in another timezone e.g.
// to ZoneId.of("America/New_York")
ZonedDateTime zdtNewYork = zdtDefaultTz.withZoneSameInstant(ZoneId.of("America/New_York"));
System.out.println(zdtNewYork);
}
}
样本运行的输出:
2021-07-25T15:48:10.584414+01:00[Europe/London]
2021-07-25T10:48:10.584414-04:00[America/New_York]
从 Trail: Date Time 了解有关现代日期时间 API 的更多信息。
* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。
【讨论】: