I have implemented a LocalDateTimeConverter
in my library, Suitcase, here. Keep in mind that this extends my BaseConverter
class here. Note: This is all in Kotlin.
If you want to implement yourself, I would recommend storing is as a String as opposed to a timestamp. If you check out the links above, you will see that I first convert the date to a String using toString()
, and then back to a LocalDateTime
using the parse()
function.
Here it is in Java:
public class LocalDateTimeConverter {
@TypeConverter
public static LocalDateTime toDate(String dateString) {
if (dateString == null) {
return null;
} else {
return LocalDateTime.parse(dateString);
}
}
@TypeConverter
public static String toDateString(LocalDateTime date) {
if (date == null) {
return null;
} else {
return date.toString();
}
}
}
Edit:
The reason the code you are using above isn't working is because in your toTimestamp()
function you are simply asking for the hour of day as a Long
. So given a LocalDateTime
that is January 1, 2019, 12:00 PM, you are storing 12
. So in toDate
, you are asking to convert the timestamp 12
to a LocalDateTime
, which would be 12 milliseconds after midnight on January 1, 1970.
You can choose to continue using timestamps to store your date by simply changing that line in toTimestamp()
to date.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
. This will give you the actual timestamp for the LocalDateTime
in the current time zone. Be aware of timezones here: as you are using the system's default timezone to save/load to/from the database, you may get a wrong value should the system changes timezones. If I use your app in New York, and then reopen the app in San Francisco all of the times will be off by 3 hours. It would be better to use a set timezone to save/load, and then convert that to the device's current timezone.