使用java8将字符串转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35665464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting string to date using java8
提问by user3509208
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?
我正在尝试使用 java 8 将字符串转换为特定格式。下面是我的代码。即使在提到格式模式为 MM/dd/yyyy 之后,我收到的输出也是 yyyy/DD/MM 格式。有人可以指出我做错了什么吗?
String str = "01/01/2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate dateTime = LocalDate.parse(str, formatter);
System.out.println(dateTime);
回答by Ankit Bansal
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.
LocalDate 是一个日期对象。它不是 String 对象,因此显示日期输出字符串的格式将取决于 toString 实现。
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:
您已将其正确转换为 LocalDate 对象,但如果要以特定字符串格式显示日期对象,则需要相应地对其进行格式化:
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.
通过这种方式,您可以通过提供格式化程序将日期转换为您想要的任何字符串格式。
回答by marcospereira
That is because you are using the toString methodwhich states that:
那是因为您使用的是toString 方法,该方法指出:
The output will be in the ISO-8601 format uuuu-MM-dd.
输出将采用 ISO-8601 格式 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
methodlike this:
将DateTimeFormatter
你传送到LocalDate.parse
只是用来创建LocalDate
,但它不是“附加”到创建的实例。您将需要使用这样的LocalDate.format
方法:
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
回答by Zoka
You can use SimpleDateFormatclass for that purposes. Initialize SimpleDateFormatobject with date format that you want as a parameter.
为此,您可以使用SimpleDateFormat类。使用您想要作为参数的日期格式初始化SimpleDateFormat对象。
String dateInString = "27/02/2016"
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(dateInString);