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);
Java 8 uses Date-Time API that provides parse() methods to convert the String value into the Date-Time value. For basic parsing rules, there have been standards defined to represent the String value for the date and time in either ISO_LOCAL_TIME or ISO_LOCAL_DATE format.
Java 8 provides APIs for the easy formatting of Date and Time: LocalDateTime localDateTime = LocalDateTime. of(2015, Month. JANUARY, 25, 6, 30);
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
That is because you are using the toString method which states that:
The output will be in the ISO-8601 format uuuu-MM-dd.
The DateTimeFormatter
that you passed to LocalDate.parse
is used just to create a LocalDate
, but it is not "attached" to the created instance. You will need to use LocalDate.format
method like this:
String str = "01/01/2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate dateTime = LocalDate.parse(str, formatter);
System.out.println(dateTime.format(formatter)); // not using toString
You can use SimpleDateFormat class for that purposes. Initialize SimpleDateFormat object with date format that you want as a parameter.
String dateInString = "27/02/2016"
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(dateInString);
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:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
System.out.println(dateTime.format(formatter))
This way you can convert date to any string format you want by providing formatter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With