Reputation: 8414
I have a bean which contains a field of type java.lang.String
. This field holds free-form text which can represent a number, string, or date. When the field represents a date, I render a calendar (primefaces) on the screen, otherwise an input box is rendered.
The problem I'm having is that after the user selects the date via the calendar, I would like the date string that gets written to my free-form field to have a specific format (MM/dd/yyyy). Currently the string that gets set has the default format you get when you do a toString()
on a java.util.Date
object.
Does anyone know how I can control the format of the string that gets written to my field?
Thanks.
Upvotes: 3
Views: 6542
Reputation: 66
Assuming that you have an String field called "freeText" with their getter and setter, add a getter that returns Date and a setter that convert a Date to String. Both using the format that you want. For example:
String freeText;
String getFreeText() {
return this.freeText;
}
void setFreeText(String freeText) {
this.freeText = freeText;
}
Date getFreeTextAsDate() {
try {
if (this.freeText == null) {
return null;
}
return new SimpleDateFormat("MM/dd/yyyy").parse(this.freeText);
} catch (ParseException e) {
return null;
}
}
void setFreeTextAsDate(Date freeTextAsDate) {
if (freeTextAsDate== null) {
this.freeText = null;
} else {
this.freeText = new SimpleDateFormat("MM/dd/yyyy").format(freeTextAsDate);
}
}
Finally, use freeTextAsDate in the calendar:
<p:calendar value="#{yourBean.freeTextAsDate}" />
Upvotes: 1
Reputation: 5116
You can use the pattern
attribute of primefaces calendar
: pattern="MM/dd/yyyy"
, or you can use java's class SimpleDateFormat
for server side format and data manipulation(for better control over your string date):
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date myReceivedDate = dateFormat.parse(receivedStringDate);
String myNewDate = dateFormat.format(myReceivedDate);
Upvotes: 0
Reputation: 51030
I think the following should do it:
<p:calendar value="#{calTestBean.dateStr}" pattern="MM/dd/yyyy">
<f:convertDateTime pattern="MM/dd/yyyy"/>
</p:calendar>
Upvotes: 1