1

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!.

Menelaos
  • 23,508
  • 18
  • 90
  • 155
Vik K
  • 33
  • 4
  • What you see in the debugger is formatted by a custom formatter of your IDE. `toString()` has it's own format. However, you should use java conversion methods to change between date and localdate. – Menelaos Feb 04 '20 at 22:49
  • 1
    Don't rely on the result from `toString` – MadProgrammer Feb 04 '20 at 23:10
  • You can’t. A `Date` hasn’t got, as in cannot have a format. See [this question](https://stackoverflow.com/questions/6262310/display-java-util-date-in-a-specific-format) or [my answer here](https://stackoverflow.com/a/52485250/5772882). Also what do you want an old-fashioned `Date` for when you can have a modern `LocalDate`? – Ole V.V. Feb 05 '20 at 06:31

2 Answers2

3

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

Menelaos
  • 23,508
  • 18
  • 90
  • 155
-1

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.

Renato
  • 2,077
  • 1
  • 11
  • 22
  • While it’s correct please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Feb 05 '20 at 06:33