问题
I have a user object, and the User is having a field DOB (Date of Birth) I have stored that field as a calendar inside the User BO.
Something like this:
public class UserBO {
private Calendar dateOfBirth;
public Calendar getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Calendar dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
Now I need to display this field as a Date field in thymeleaf and not a text field. I need a date field since I like the date picker :)
This is what I have so far
<label class="col-xs-2">Date of Birth</label>
<div class="col-xs-2">
<input type="date" class="form-control" th:field="*{dateOfBirth}" placeholder="Date of Birth" />
</div>
But this gives me the output as
this is not what I am expecting. I am expecting an actual date to be populated from the service but its showing me this as above.
I have read about Seralization & deserialization of Calendar objects and writing some sort of converters but I did not get full context why is this required. plus when I have seen examples with
input type="text" and the dates are populated correctly. SO can some one please guide me what is the fundamentals for this conversion and and example of how this should be done would be nice.
thanks
回答1:
Firstly you need not use Calendar
. A simple java.util.Date
is sufficient.
So you can use bootstrap datepicker for client side date picker. Suppose the format the date picker expects is mm/dd/yyyy
, then you can use Thymeleaf expression object to format the dateOfBirth
as ${#dates.format(dateOfBirth, 'MM/dd/yyyy')}
Note that the format used by Thymeleaf is similar to the one used by SimpleDateFormat
and the one used by Datepicker can be found from the docs here
回答2:
When you are using input elements of type date, the date value should be always formatted as yyyy-mm-dd. The displayed date format will be chosen based on the set locale of the user's browser.
Try this code:
<input type="date" value="10/14/2016" class="form-control" id="dateOfBirth"
th:value="${#calendars.format(dateOfBirth,'yyyy-MM-dd')}" th:name="dateOfBirth" />
来源:https://stackoverflow.com/questions/47210812/view-calendar-objects-in-thymeleaf-forms-as-date-types