How to convert Joda instant to LocalDate and vice-versa?
Asked Answered
P

1

7

I understand that an Joda Instant is similiar to Unix Timestamp in that it stores the number of milliseconds since 1.1.1970. So I want to insert this in my Android SQLite Database as INTEGER. But in my app, I work with Joda LocalDate, so I need to convert LocalDate to Instants and vice-versa.

Can anyone tell me how?

Promptitude answered 10/3, 2015 at 19:4 Comment(0)
P
8

In order to convert a LocalDate to an Instant, you need the time of day and a time zone. The class LocalDate offers the method toDateTime() so you can use this example and adjust it to your needs:

LocalDate date = new LocalDate();
LocalTime time = LocalTime.MIDNIGHT;
DateTimeZone zone = DateTimeZone.getDefault();
Instant instant = date.toDateTime(time, zone).toInstant();

The reverse direction also needs a timezone.

Instant instant = Instant.now();
DateTimeZone zone = DateTimeZone.getDefault();
LocalDate date = instant.toDateTime(zone).toLocalDate();

Although it is possible to leave out the zone arguments in Joda-Time (which shall mean the system time zone) I recommend to specify it explicitly to make the timezone dependency clearer. The same instant/moment can be related to different dates around the globe (due to midnight change at some locations or due to crossing the international date line).

Posterior answered 11/3, 2015 at 15:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.