In my JSF managed bean I have declared startDate as java.utilDate type and I have getters and setters as well. From database startDate is date type.
When I receive value format is of default type and I format the date
SimpleDateFormat df = new SimpleDateFormat(" dd MMM yyyy");
Date oneDate = new Date(startDate);
df.format(oneDate);
Issue I am facing is df.format(oneDate);
returns String.
Is it possible to convert df.format(oneDate)
back to Date, so that I need not have to
change my startDate data type.
Any help is highly appreciated.
Thanks
As per the comment on the question:
@BalusC I agree with what you said, it is better to format in UI. So I added the following in my jsf page.
<p:inputText value="#{vacationschedule.convertTime(vacationschedule.selectedRow.startDate)}">
and
convertTime
method in managedBean ispublic String convertTime(Date time){ Date date = new Date(); Format format = new SimpleDateFormat("yyyy MM dd"); return format.format(date); }
<p:inputText>
is showing correctly however if I would like to use<p:calendar>
then I am getting errorSEVERE: java.lang.IllegalArgumentException: Cannot format given Object as a Date
You're looking for the solution in the wrong direction. Human-targeted formatting has to be done in the View (UI) side, not in the Model side, let alone the Controller side.
To present a Date
object in a human friendly pattern in a JSF component, you should be using <f:convertDateTime>
tag provided by standard JSF component set:
<p:inputText value="#{vacationschedule.selectedRow.startDate}">
<f:convertDateTime pattern="yyyy MM dd" />
</p:inputText>
This way you can keep the property just Date
all the time. This way you will also be able to save the edited value (which wouldn't be possible with your initial attempt!).
As to the PrimeFaces' <p:calendar>
component, it has a pattern
attribute exactly for this purpose:
<p:calendar value="#{vacationschedule.selectedRow.startDate}" pattern="yyyy MM dd" />
Download and consult the PrimeFaces Users Guide to learn about all available attributes.
Using the same SimpleDateFormat
object you created,
df.parse(yourDateString);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With