0

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

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.

Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
user1548157
  • 81
  • 1
  • 2
  • 7

1 Answers1

3

Use MM that represents Month instead of mm that represents minutes.

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

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-dd pattern.

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

Braj
  • 46,415
  • 5
  • 60
  • 76
  • LocalDate.parse is not a method in LocalDate. I can do LocalDateTime.parse I think but not LocalDate.parse. I want to return LocalDate not LocalDateTime – user1548157 May 18 '14 at 17:57
  • Find it here [LocalDate.parse()](http://joda-time.sourceforge.net/apidocs/org/joda/time/LocalDate.html#parse%28java.lang.String,%20org.joda.time.format.DateTimeFormatter%29). check the imports please – Braj May 18 '14 at 18:02
  • Hey thanks Braj. I have imported mport org.joda.time.LocalDate. I am usning Java 1.7. Maybe thats the problem. – user1548157 May 18 '14 at 18:06
  • Is the issue resolved if yes then close the thread. – Braj May 18 '14 at 18:06
  • So, maybe I need to do it the hard way. Use DateTime as well http://stackoverflow.com/questions/8746084/string-to-localdate – user1548157 May 18 '14 at 18:14
  • I have `joda-time-2.1.jar` in my project. – Braj May 18 '14 at 18:26