我想以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());
Run Code Online (Sandbox Code Playgroud)
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());
Run Code Online (Sandbox Code Playgroud)
OUTPUT
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
Run Code Online (Sandbox Code Playgroud)
我想要的是,当地日期显示在15点钟,而utc日期显示在14点......现在,这似乎有效......
----- EDIT3 - 最终解决方案-----
希望这是一个很好的解决方案...我想,我尊重所有的tipps ...
DateTimeZone tz = DateTimeZone.getDefault();
DateTime nowUTC = new DateTime(DateTimeZone.UTC);
DateTime nowLocal = nowUTC.withZone(tz);
// This will generate DIFFERENT Dates!!! As I want it!
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());
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 73
你做得比你需要的要复杂得多:
DateTime dt = new DateTime(DateTimeZone.UTC);
Run Code Online (Sandbox Code Playgroud)
根本不需要转换.如果您发现实际需要转换,则可以使用withZone
.我建议你避免通过LocalDateTime
,但是,由于时区转换,你可能会丢失信息(两个不同的时刻可能在同一时区有相同的本地时间,因为时钟会返回并重复本地时间.
说完所有这些之后,为了可测试性,我个人喜欢使用Clock
允许我获取当前时间的界面(例如,作为一个Instant
).然后,您可以使用依赖注入在生产中运行时注入实际系统时钟,并使用具有预设测试时间的假时钟.Java 8的java.time
软件包内置了这个想法,顺便说一下.
Kob*_*net 11
您也可以使用静态方法现在这使得它更可读
DateTime.now(DateTimeZone.UTC)
Run Code Online (Sandbox Code Playgroud)
用这个
DateTime.now().withZone(DateTimeZone.UTC)
Run Code Online (Sandbox Code Playgroud)
如果你想格式化,你可以使用
DateTime.now().withZone(DateTimeZone.UTC).toString("yyyyMMddHHmmss")
Run Code Online (Sandbox Code Playgroud)