Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Joda instant to LocalDate and vice-versa?

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?

like image 358
mrd Avatar asked Mar 10 '15 19:03

mrd


1 Answers

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

like image 134
Meno Hochschild Avatar answered Oct 29 '22 05:10

Meno Hochschild