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?

mrd
  • 4,561
  • 10
  • 54
  • 92

1 Answers1

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).

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126