Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

java - 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...