0

I am trying to parse LocalDate to date in my Java code but I keep getting the following error:

{code: "unknown.unexpected", detail: "Text '02/28/1936' could not be parsed at index 0", meta: null}

My code is as follows:

private Date dateOfBirth;
public SearchByDateCommand(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth != null ? Date.valueOf(dateOfBirth) : null;
}

What could I be doing wrong here?

ermalsh
  • 191
  • 1
  • 16
  • Which `Date` type is this? I can't see a `Date.valueOf` method in `java.util.Date`. – Jon Skeet Jun 12 '19 at 19:04
  • @JonSkeet using java.sql.date – ermalsh Jun 12 '19 at 19:05
  • Please edit the question to clarify that then, given that `java.util.Date` is far more commonly used than `java.sql.Date`. – Jon Skeet Jun 12 '19 at 19:06
  • 1
    I'm surprised that the code you've shown throws the exception you've described though. Could you please include the stack trace? Are you certain that it's getting as far as the body of that method at all? – Jon Skeet Jun 12 '19 at 19:08

1 Answers1

1

Use this:

private Date dateOfBirth;
public SearchByDateCommand(LocalDate dateOfBirth) {
    this.dateOfBirth = dateOfBirth != null ? Date.from(dateOfBirth.atStartOfDay(ZoneId.systemDefault()).toInstant()) : null;
}

You will have to add a time to the LocalDate, interpret the date and time within a time zone, get the number of seconds / milliseconds since epoch, and lastly, create a java.util.Date.

Faraz
  • 6,025
  • 5
  • 31
  • 88