Java 如何在 JodaTime 中将格式为 yyyymmdd 的字符串转换为 LocalDate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23724749/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:54:05  来源:igfitidea点击:

How to convert a String of format yyyymmdd to LocalDate in JodaTime

javajodatime

提问by user1548157

I have a String in the form "20140518". How to convert it into LocalDate object

我有一个“20140518”形式的字符串。如何将其转换为 LocalDate 对象

I tried this

我试过这个

this.todayDate = new LocalDate(val);
System.out.println(todayDate.toString("yyyy-mm-dd"))

When I try dumping this to standard output it dumps like 20140518-junk-junk. That it dumps a garbage string . I thought it would dump like 2014-05-18.

当我尝试将其转储到标准输出时,它会转储像 20140518-junk-junk。它转储垃圾字符串。我认为它会像 2014-05-18 一样倾倒。

回答by Braj

Use MMthat represents Month instead of mmthat represents minutes.

使用MM代表月份而不是mm代表分钟。

Use LocalDate.parse()instead of new LocalDate()to construct the LocalDateobject.

使用LocalDate.parse()代替new LocalDate()来构造LocalDate对象。

DateTimeFormatter format = org.joda.time.format.DateTimeFormat.forPattern("yyyyMMdd");
LocalDate lDate = org.joda.time.LocalDate.parse("20140518", format);
System.out.println(lDate);

output:

输出:

2014-05-18


org.joda.time.LocalDate#toString()be default uses yyyy-MM-ddpattern.

org.joda.time.LocalDate#toString()默认使用yyyy-MM-dd模式。

You don't need to use todayDate.toString("yyyy-MM-dd").

您不需要使用todayDate.toString("yyyy-MM-dd").