0

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

9
  • 1
    The result is not wrong. It's just that Date.toString() produces the wrong output for really old dates. Commented Apr 27, 2023 at 4:37
  • it's not the same, because at my case i'm loosing some days Commented Apr 27, 2023 at 4:38
  • @Sweeper i need it to have to correct output otherwise it's considered wrong Commented Apr 27, 2023 at 4:39
  • There is nothing to solve. The value in the Date is correct. Just give it to whatever API you are using. If you want it to display the correct date as a String, convert it back to a LocalDate. You can see that it is the same LocalDate you had. Commented Apr 27, 2023 at 4:41
  • 2
    What do you need to handle a 1250 years old date for? You need to beware of the difference between the Julian calendar in effect back then and the proleptic Gregorian calendar that LocalDate uses. So both days, 16 July and 20 July, are correct, they are just given in different calendar systems. If you read the date July 20 in a source from back then, then it’s the Julian calendar that you need, that is, LocalDate is not the right class to use, sorry. Other than that you are doing the conversion in the correct way. Commented Apr 27, 2023 at 8:39

1 Answer 1

0

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks that solve it, not sure too about the root cause
The root cause is in my comment under the question: LocalDate and Date use two different calendar systems, the proleptic Gregorian calendar and the Julian calendar, respectively.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.