Reputation: 303
In my application, I have to deal with a Date that comes as a String, formatted as yyyy-MM-dd. I can't change the underlying class. On the view, for user convenience I want it to be displayed in dd.MM.yyyy format.
From what I understand, f:convertDateTime> only works on java.util.Date, not on Strings that just pretend to be Dates. So I wrote my own converter:
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
try {
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
Date tempDate = inputFormat.parse((String) value);
SimpleDateFormat outputFormat = new SimpleDateFormat("dd.MM.yyyy");
return outputFormat.format(tempDate);
}
catch (ParseException e) {
return null;
}
}
This works, but it just feels wrong. Converting from a String to a date and back to a different String. Also, I like how convertDateTime deals with timezones and user locale which is completely ignored in this approach.
Is there a better solution? Like parsing a date and then passing it through f:convertDateTime?
Upvotes: 2
Views: 4792
Reputation: 2219
Back end (Bean):
String string = "2014-05-14";
Date date = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(string);
System.out.println(date); // Sat May 14 00:00:00 BOT 2014
setDate(date); //Set date in bean
Front end (Reference that field in bean within value):
<h:outputText value="#{bean.date}">
<f:convertDateTime pattern="dd.MM.yyyy" timeZone="EST" type="date" />
</h:outputText>
Haven't tested it or anything... Is that kinda what you are looking for?
Upvotes: 2