Converting string to date using java8

六月ゝ 毕业季﹏ 提交于 2020-01-22 14:07:06

问题


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);

回答1:


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



回答2:


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.




回答3:


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);


来源:https://stackoverflow.com/questions/35665464/converting-string-to-date-using-java8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!