使用java8将字符串转换为日期 [英] Converting string to date using java8
问题描述
我正在尝试使用Java 8将字符串转换为日期,并将其转换为某种格式.下面是我的代码.即使在将格式模式提到为MM/dd/yyyy之后,我收到的输出也是yyyy/DD/MM格式.有人可以指出我做错了吗?
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);
推荐答案
That is because you are using the toString method which states that:
输出将采用ISO-8601格式uuuu-MM-dd.
The output will be in the ISO-8601 format uuuu-MM-dd.
您传递给LocalDate.parse
的DateTimeFormatter
仅用于创建LocalDate
,但并不附加"到创建的实例上.您将需要使用
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
这篇关于使用java8将字符串转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!