问题
import java.util.*;
import java.lang.*;
import java.io.*;
import java.time.*;
import java.time.format.*;
import java.text.*;
public class ConvertStringToDate {
public static void main(String[] args)throws Exception {
String date = "2020-06-14";
DateTimeFormatter Stringformatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// convert String to LocalDate
LocalDate localDate = LocalDate.parse(date, Stringformatter);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String formattedDate = localDate.format(formatter); // output here is as expected 14.06.2020
// facing issues when converting back to localDate with defined pattern,
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter); // expected output is 14.06.2020 but getting a LocalDate formatted 2020-06-14
// System.out.println(parsedDate);
// System.out.println(parsedDate.getClass().getName());
}
}
Apologizes for my explanation early days with java. Basically i am trying to convert input string "2020-06-14" into a localDate with a custom pattern "dd.MM.yyyy" in the end trying to have a date object not a String. Is there an other way to achieve it.
回答1:
A date has no format. Therefore when you write
//expected output is 14.06.2020 but getting a LocalDate formatted 2020-06-14
your expectation is simply wrong. The date is parsed according to the formatter but how the date represents the parsed values and how it chooses to display them afterwards no longer has any connection to the formatter.
The only way to get your format back is to write parsedDate.format(formatter)
once again and you are back where you started, which is what formattedDate
was already.
来源:https://stackoverflow.com/questions/62372392/unable-to-convert-string-to-localdate-with-custom-pattern