I am trying to convert a string to date using java 8 to a certain format. Below is my code. Even after mentioning the format pattern as MM/dd/yyyy the output I am receiving is yyyy/DD/MM format. Can somebody point out what I am doing wrong?
String str = "01/01/2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate dateTime = LocalDate.parse(str, formatter);
System.out.println(dateTime);
You can use SimpleDateFormat class for that purposes. Initialize SimpleDateFormat object with date format that you want as a parameter.
That is because you are using the toString method which states that:
The
DateTimeFormatter
that you passed toLocalDate.parse
is used just to create aLocalDate
, but it is not "attached" to the created instance. You will need to useLocalDate.format
method like this:LocalDate is a Date Object. It's not a String object so the format in which it will show the date output string will be dependent on toString implementation.
You have converted it correctly to LocalDate object but if you want to show the date object in a particular string format, you need to format it accordingly:
This way you can convert date to any string format you want by providing formatter.