Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to date using java8

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);
like image 746
user3509208 Avatar asked Feb 27 '16 03:02

user3509208


People also ask

Which interface in Java 8 provides for parsing a string to date?

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.

How do I format a date in Java 8?

Java 8 provides APIs for the easy formatting of Date and Time: LocalDateTime localDateTime = LocalDateTime. of(2015, Month. JANUARY, 25, 6, 30);

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.


3 Answers

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
like image 173
marcospereira Avatar answered Oct 09 '22 10:10

marcospereira


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);
like image 21
Zoka Avatar answered Oct 09 '22 08:10

Zoka


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.

like image 44
Ankit Bansal Avatar answered Oct 09 '22 10:10

Ankit Bansal