Reputation: 33
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
Reputation: 26549
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.
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
.
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);
}
Upvotes: 3
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