Converting string to date using java8

2020-06-11 05:12发布

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

3条回答
We Are One
2楼-- · 2020-06-11 05:38

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);
查看更多
家丑人穷心不美
3楼-- · 2020-06-11 05:44

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
查看更多
神经病院院长
4楼-- · 2020-06-11 05:52

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.

查看更多
登录 后发表回答