Vik K
Vik K

Reputation: 33

Date format issue using LocalDate

I need to convert a Date object(it shows this in debug mode---> "Mon Sep 23 00:00:00 EDT 2019") to another Date object having "yyyy-MM-dd" format.

I tried the following code, but I get a runtime error saying:

java.time.format.DateTimeParseException: Text 'Mon Sep 23 00:00:00 EDT 2019' could not be parsed at index 0.

LocalDate localDate = LocalDate.parse(date.toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
Date result = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

Thanks for your help!.

Upvotes: 1

Views: 573

Answers (2)

Menelaos
Menelaos

Reputation: 26549

Your error

What you see in the debugger is formatted by a custom formatter of your IDE. Date.toString() has it's own format. However, you should use java conversion methods to change between date and localdate

Here is an except on date.toString():

The toString() method of Java Date class converts this date object into a String in form “dow mon dd hh:mm:ss zzz yyy”. This method overrides toString in class object.

Source

The pattern "yyyy-MM-dd" is not compatible with this.

Why are you doing this however? There are better ways to convert a Date into a LocalDate.

Convert Date to LocalDate (& Vice Versa)

Try the following:

public LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
    return dateToConvert.toInstant()
      .atZone(ZoneId.systemDefault())
      .toLocalDate();
}

public Date convertToDateViaSqlDate(LocalDate dateToConvert) {
    return java.sql.Date.valueOf(dateToConvert);
}

Source

Upvotes: 3

Renato
Renato

Reputation: 2177

Date objects are Date, nothing else. String rapresentation of Date objects could have format. I think this

new SimpleDateFormat('yyyy-MM-dd').format(date);

is the only thing you need.

Upvotes: -1

Related Questions