Joda time from string LocalDateTime to LocalDate
I am using JodaTime to get the date and time the account was created. Format
2017-04-05T12:38:35.585
When I receive this, I store it in my database as a string, so I looked for ways to format this from a string to LocalDate, but have not been successful with everything I have found on the internet. My next step is a terrible solution, in my opinion, to loop through the line until I find the T and delete everything after it. So I stayed with
2017-04-05.
But ideally, if possible, the date should be
05/04/2017
source to share
Use ISODateTimeFormat
to get LocalDateTime
, and get out of it LocalDate
. Be careful using the rightLocale
String input="2017-04-05T12:38:35.585";
LocalDateTime ldt = ISODateTimeFormat.localDateOptionalTimeParser()
.withLocale(Locale.ENGLISH)
.parseLocalDateTime(input);
System.out.println(ldt.toLocalDate());//prints 2017-04-05
source to share
I am using joda-time 2.7 .
LocalDateTime
the class has a constructor that takes in String
and parses it. Then you just call the method toString()
with the template you want:
String input = "2017-04-05T12:38:35.585";
LocalDateTime d = new LocalDateTime(input);
System.out.println(d.toString("dd/MM/yyyy"));
Output:
05/04/2017
Note : you can also use ISODateTimeFormat
to parse and DateTimeFormatter
instead toString()
to get the result:
LocalDateTime d = ISODateTimeFormat.localDateOptionalTimeParser().parseLocalDateTime(input);
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/yyyy");
System.out.println(fmt.print(d));
The output will be the same.