I'm having some difficulty finding the right way to parse a date.
I receive the date as a String in the following format: '2018-10-18 00:00:00'
I need to convert it to 18/10/2018 and store in a variable startDate
I then need a new variable to hold an endDate variable so roll the date forward by a week.
My code:
public String getStartDate(String startDate){
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate localStartDate = LocalDate.parse(startDate, formatter);
String startDateFormatted = localStartDate.format(formatter);
return startDateFormatted;
}
public LocalDate getEndDate(String startDate) {
LocalDate localEndDate = LocalDate.parse(getStartDate(startDate)).plusDays(7);
return localEndDate;
}
My error is:
java.time.format.DateTimeParseException: Text '2018-10-18 00:00:00' could
not be parsed at index 4
Index 4 suggests the '-' char. Not sure the formatter pattern for removing the ISO time format that's in the original String
I'm wading through the Javadocs now but can anyone tell me how I can fix?
Your input format is wrong. Try this:
public String getStartDate(String startDate)
{
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy");
return LocalDate.parse(startDate, inputFormat).format(outputFormat);
}