[英]How to convert ZonedDateTime/OffsetDateTime to Date using ThreeTenABP?
Using the ThreeTen Android Backport library, 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;但我不能在 Android 上使用它; specifically
Date.from(Instant instant)
is missing.特别是
Date.from(Instant instant)
缺失。
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.如果有更好的方法,请随时指出。
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.