简体   繁体   English

如何将字符串转换为本地日期

[英]How to convert String to LocalDate

String date = "1992-07-25";

LocalDate dt = LocalDate.parse(date);

System.out.println(dt) // 1992-07-25 ( output )

DateTimeFormatter f =  DateTimeFormatter.ofPattern("d/MM/yyyy");

String s1 = f.format(dt); 

System.out.println(s1) // 25/07/1992 ( output in string format )

I want this (String) s1 to convert into LocalDate of pattern (LocalDate - dd/MM/yyy)我希望这个(字符串)s1 转换为模式的 LocalDate (LocalDate - dd/MM/yyy)

Output - 25/07/1992 should be LocalDate Type, not String输出 - 25/07/1992 应该是 LocalDate 类型,而不是字符串

When you are printing LocalDate instance, it is actually calling toString() method of LocalDate class.当您打印LocalDate实例时,它实际上是在调用LocalDate类的toString()方法。 And according to javadoc 11 , this method根据javadoc 11 ,这种方法

Outputs this date as a String, such as 2007-12-03.
The output will be in the ISO-8601 format uuuu-MM-dd.

So you are seeing, it will always print in uuuu-MM-dd format.所以你看到了,它总是以uuuu-MM-dd格式打印。

Think LocalDate as a DATE just, from where you can get the info of that particular date.LocalDate视为DATE ,您可以从中获取该特定日期的信息。 When you are printing LocalDate itself, it has no meaning actually.当您打印 LocalDate 本身时,它实际上没有任何意义。 If you need to show the date in any particular format, convert it into String, which you can do already.如果您需要以任何特定格式显示日期,请将其转换为字符串,您已经可以这样做了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM