Search code examples
javadatejava-timelocaldatejava.util.date

Converting LocalDate to java.util.Date


I'm trying to convert a java.time.LocalDate to java.util.Date, but I lose some days in the process.

Here the code that shows the issue:

public static void main(String[] args) {
    var localDate = LocalDate.of(775, 7, 20);
    var date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    System.out.println("date = " + date);
}

As you can see, I have a LocalDate that's in year 775, month 7 and day 20.

But when I convert it to Date it becomes in year 775, month 7 and day 16.

So 4 days are missing.

Is there a way of converting without a loss in days?

PS: I know that I should not mix legacy Date API with the new Date API but I'm limited by a closed source ERP that uses java.util.Date


Solution

  • Not sure of the root cause for such difference in the days, but below work around might be helpful in your context:

        var localDate = LocalDate.of(775, 7, 20);
        var instant = Calendar.getInstance();
        instant.set(localDate.getYear(), localDate.getMonthValue() - 1 , localDate.getDayOfMonth());
        var date = instant.getTime();
        System.out.println("date = " + date);