What's the proper way to migrate from Date to LocalDate in Java 8?

Viewed 114

I'm currently working on a legacy codebase where Date was used everywhere, and continues to be used because Dates are everywhere (entities contain Dates, services expect Dates, etc.). For some cases where the time portion shouldn't be used, we remove it from the Date object by using basically the following standard snippet in a utility method.

final Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();

I'd like to start using LocalDate for these cases. From what I could find, the standard recommended way of converting is (at least in Java 8):

date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

What I'm a bit uneasy about is the atZone(ZoneId.systemDefault()) part. Could I get different LocalDates depending on which system the code is executed? I guess I could extract the year, month and day from the Date and construct a new LocalDate by explicitly passing the year, month and day, but I would like to use the standard solution if I can be sure the semantics will be maintained (i.e. I won't get any off-by-one-day errors). I first tried:

date.toInstant().atOffset(ZoneOffset.UTC).toLocalDate()

but this did give an instance where the Date and LocalDate where off by 1 day.

Any pointers appreciated!

0 Answers
Related