Search code examples
javadatetimedatetime-formatjava-timelocaldate

How to convert String inot a LocalDate object


I have a String value as follows

2018-12-05 18:11:27.187

How can I can convert it into a LocalDate object based on that format "MM/dd/YYYY HH:mm:ss" ?


Solution

  • a LocalDate object is what it is. It has no format; it is an object with methods; these methods make it do stuff.

    You can for example ask a localdate to return the year of the date it represents. You can also ask it to render itself as a string using some format. That string is then not a LocalDate (it is a String).

    Furthermore, a localdate represents a date. Hence the name. 'hour' is not part of a date. YYYY is the pattern for week based year. You don't want that.

    So, fixing your misconceptions, we end up with:

    DateTimeFormatter inFormat = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
    DateTimeFormatter outFormat = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss");
    
    LocalDateTime when = LocalDateTime.parse("2018-12-05 18:11:27.187", inFormat);
    System.out.println(outFormat.format(when));