JodaTime - 如何获取当前时间的UTC时间

12 浏览
0 Comments

JodaTime - 如何获取当前时间的UTC时间

我想要获取当前的UTC时间。我目前的做法是(仅用于测试目的):

DateTime dt = new DateTime();
DateTimeZone tz = DateTimeZone.getDefault();
LocalDateTime nowLocal = new LocalDateTime();
DateTime nowUTC = nowLocal.toDateTime(DateTimeZone.UTC);
Date d1 = nowLocal.toDate();
Date d2 = nowUTC.toDate();
L.d("tz: " + tz.toString());
L.d("local: " + d1.toString());
L.d("utc: " + d2.toString());

- `d1`是我的本地时间,没问题

- `d2`是我的本地时间加1,但应该是减1...

我的本地时区是UTC+1(根据调试输出和此处列表:https://www.joda.org/joda-time/timezones.html)...

我如何正确地从一个时区转换到另一个时区(包括毫秒表示)?

编辑

我需要日期/毫秒...不是关于正确显示时间...

编辑2

现在,在评论和答案的帮助下,我尝试了以下代码:

DateTimeZone tz = DateTimeZone.getDefault();
DateTime nowLocal = new DateTime();
LocalDateTime nowUTC = nowLocal.withZone(DateTimeZone.UTC).toLocalDateTime();
DateTime nowUTC2 = nowLocal.withZone(DateTimeZone.UTC);
Date dLocal = nowLocal.toDate();
Date dUTC = nowUTC.toDate();
Date dUTC2 = nowUTC2.toDate();
L.d(Temp.class, "------------------------");
L.d(Temp.class, "tz    : " + tz.toString());
L.d(Temp.class, "local : " + nowLocal +     " | " + dLocal.toString());
L.d(Temp.class, "utc   : " + nowUTC +       " | " + dUTC.toString()); // <= WORKING SOLUTION
L.d(Temp.class, "utc2  : " + nowUTC2 +      " | " + dUTC2.toString());

输出结果为:

tz    : Europe/Belgrade
local : 2015-01-02T15:31:38.241+01:00 | Fri Jan 02 15:31:38 MEZ 2015
utc   : 2015-01-02T14:31:38.241 | Fri Jan 02 14:31:38 MEZ 2015
utc2  : 2015-01-02T14:31:38.241Z | Fri Jan 02 15:31:38 MEZ 2015

我希望本地日期显示15点,UTC日期显示14点...

目前,这个方法似乎可行...

----- 编辑3 - 最终解决方案 -----

希望这是一个好的解决方案...我认为它考虑了我得到的所有提示...

DateTimeZone tz = DateTimeZone.getDefault();
DateTime nowUTC = new DateTime(DateTimeZone.UTC);
DateTime nowLocal = nowUTC.withZone(tz);
// 这将生成不同的日期!!!正是我想要的!
Date dLocal = nowLocal.toLocalDateTime().toDate();
Date dUTC = nowUTC.toLocalDateTime().toDate();
L.d("tz    : " + tz.toString());
L.d("local : " + nowLocal +     " | " + dLocal.toString());
L.d("utc   : " + nowUTC +       " | " + dUTC.toString());

输出结果为:

tz    : Europe/Belgrade
local : 2015-01-03T21:15:35.170+01:00 | Sat Jan 03 21:15:35 MEZ 2015
utc   : 2015-01-03T20:15:35.170Z | Sat Jan 03 20:15:35 MEZ 2015

0