Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java date convert string back to Date

Tags:

java

jsf

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

like image 835
Jacob Avatar asked Dec 17 '22 03:12

Jacob


2 Answers

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 is

public 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 error

SEVERE: 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.

like image 82
BalusC Avatar answered Dec 28 '22 21:12

BalusC


Using the same SimpleDateFormat object you created,

df.parse(yourDateString);
like image 31
DaveJohnston Avatar answered Dec 28 '22 21:12

DaveJohnston