How to Format Localdate Object to Mm/Dd/Yyyy and Have Format Persist

How to format LocalDate to string?

SimpleDateFormat will not work if he is starting with LocalDate which is new in Java 8. From what I can see, you will have to use DateTimeFormatter, http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html.

LocalDate localDate = LocalDate.now();//For reference
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd LLLL yyyy");
String formattedString = localDate.format(formatter);

That should print 05 May 1988. To get the period after the day and before the month, you might have to use "dd'.LLLL yyyy"

How to format LocalDateTime yyyy-MM-dd HH:mm to dd-MM-yyyy HH:mm as String for a whole list of an object which contains not only a date attribute?

You can parse the dates using Java Stream like this:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");

List<String> formattedDates = theHolidays.stream()
.map(Holiday::getUpdated)
.map(formatter::format)
.collect(Collectors.toList());

But if you're using thymeleaf, you can format your dates like this:

<tr th:each="holiday : ${holidays}">
<td th:text="${#temporals.format(holiday.updated, 'dd-MM-yyyy HH:mm')}"></td>
</tr>

Localdate.format, format is not applied

I had to use a String converter for my Datepicker.

    public String changeformat(DatePicker date) {

date.setConverter(new StringConverter<LocalDate>() {
String pattern = "MM.yyyy";
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);

{
date.setPromptText(pattern.toLowerCase());
}

@Override
public String toString(LocalDate date) {
if (date != null) {
return dateFormatter.format(date);
} else {
return "";
}
}

@Override
public LocalDate fromString(String string) {
if (string != null && !string.isEmpty()) {
return LocalDate.parse(string, dateFormatter);
} else {
return null;
}
}
});
return null;
}

It worked perfectly fine. I had to use a parameter since I'm currently using 5 Datepickers.

How to convert LocalDate from one format to another LocalDate format in java 8 without using String date?

This feature is not a responsibility of LocalDate class which is an immutable date-time object that represents a date. Its duty is not to care about the String format representation.

To generate or parse strings, use the DateTimeFormatter class.

DateTimeFormatter pattern = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String string = date.format(pattern);

Back to LocalDate, use the same pattern:

LocalDate dateParsed = LocalDate.parse(string, pattern);

But the new dateParsed will again be converted to its default String representation since LocalDate overrides toString() method. Here is what the documentation says:

The output will be in the ISO-8601 format uuuu-MM-dd.

You might want to implement your own decorator of this class which handles the formatting.



Related Topics



Leave a reply



Submit