Reputation: 335
I'm using JodaTime to get the date and time of creation of an account. The format being
2017-04-05T12:38:35.585
When I get this I store it in my database as a string so I've looked around for ways to format this from a string to LocalDate but haven't been succesful in anything I've found online. My next step is a horrible solution in my opinion to loop through the string until I find the T and remove everything after it. So I'm left with
2017-04-05.
But Ideally if possible have the date as
05/04/2017
Upvotes: 3
Views: 3570
Reputation:
I'm using joda-time 2.7.
LocalDateTime
class has a constructor that takes a String
and parses it. Then you just call toString()
method with the pattern 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 a DateTimeFormatter
instead of toString()
to get the output:
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.
Upvotes: 3
Reputation: 1254
Use the ISODateTimeFormat
to get a LocalDateTime
and from this get the LocalDate
.
Be careful to use the right Locale
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
Upvotes: 3