-5

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" ?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
angus
  • 3,210
  • 10
  • 41
  • 71
  • 5
    Dates don't have formats. Text representations of dates have formats. – Kayaman Nov 18 '20 at 17:05
  • 1
    Parse the `LocalDate` (abstraction with no specific format) and use `DateTimeFormatter` (String representation) to achieve the formatted result. – Nikolas Charalambidis Nov 18 '20 at 17:05
  • Please don't use archaic and confusing date formats. The original string is the ONLY correct way to write out a date numerically. (Dropping the milliseconds is fine, of course.) – swpalmer Nov 18 '20 at 17:25
  • 1
    Search Stack Overflow before posting. This has been addressed aman many times already, – Basil Bourque Nov 18 '20 at 17:45

2 Answers2

3

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));
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
1
  1. Firstly you need to define the pattern of your current Date and Time input
  2. Parse the current Date and Time to LocalDateTime class
  3. Print the value to the new Date and Time format you want.
LocalDateTime date = LocalDateTime.parse("2018-12-05 18:11:27.187", DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS"));

System.out.println(date.format(DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss")));
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36