Java 如何使用 ThreeTenABP 将 ZonedDateTime/OffsetDateTime 转换为日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41480485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert ZonedDateTime/OffsetDateTime to Date using ThreeTenABP?
提问by Jonik
Using the ThreeTen Android Backportlibrary, what is the simplest way to convert a ZonedDateTime
or OffsetDateTime
into an old-school java.util.Date
instance?
使用ThreeTen Android Backport库,将ZonedDateTime
或OffsetDateTime
转换为老式java.util.Date
实例的最简单方法是什么?
If I had full Java 8 libs at my disposal, this of course would be the way to do it (as in this question):
如果我有完整的 Java 8 库可供我使用,这当然是这样做的方法(如本问题所示):
Date.from(zonedDateTime.toInstant());
But I cannot use that on Android; specifically Date.from(Instant instant)
is missing.
但我不能在 Android 上使用它;具体Date.from(Instant instant)
失踪了。
采纳答案by JodaStephen
See DateTimeUtils
which handles the methods added to classes like java.util.Date
:
http://www.threeten.org/threetenbp/apidocs/org/threeten/bp/DateTimeUtils.html
查看DateTimeUtils
哪些处理添加到类中的方法,例如java.util.Date
:http:
//www.threeten.org/threetenbp/apidocs/org/threeten/bp/DateTimeUtils.html
Edit: using that, the complete code would be:
编辑:使用它,完整的代码将是:
DateTimeUtils.toDate(zonedDateTime.toInstant())
回答by Jonik
Well, one straightforward way is to get milliseconds since epoch and create the Date from that:
好吧,一种直接的方法是获取自纪元以来的毫秒数并从中创建日期:
long epochMilli = zonedDateTime.toInstant().toEpochMilli();
Date date = new Date(epochMilli);
Feel free to point out if there's some preferable way.
如果有更好的方法,请随时指出。