如何将Joda Instant转换为LocalDate,反之亦然?

mrd*_*mrd 6 sqlite android jodatime instant

我了解Joda Instant与Unix Timestamp类似,因为它存储自1.1.1970起的毫秒数。所以我想将它作为INTEGER插入我的Android SQLite数据库中。但是在我的应用程序中,我使用的是Joda LocalDate,因此我需要将LocalDate转换为Instants,反之亦然。

谁能告诉我如何?

Men*_*ild 5

为了将转换LocalDateInstant,您需要一天中的时间和一个时区。该类LocalDate提供了toDateTime()方法,因此您可以使用此示例并根据需要进行调整:

LocalDate date = new LocalDate();
LocalTime time = LocalTime.MIDNIGHT;
DateTimeZone zone = DateTimeZone.getDefault();
Instant instant = date.toDateTime(time, zone).toInstant();
Run Code Online (Sandbox Code Playgroud)

反向也需要时区

Instant instant = Instant.now();
DateTimeZone zone = DateTimeZone.getDefault();
LocalDate date = instant.toDateTime(zone).toLocalDate();
Run Code Online (Sandbox Code Playgroud)

尽管可以在Joda-Time中省略zone参数(这将意味着系统时区),但我还是建议明确指定它以使时区依赖性更加清晰。相同的瞬间/时刻可能与全球各地的不同日期相关(由于某些位置的午夜更改或由于跨越国际日期线)。