Date Convert Java Date to Date

In my JSF managed bean, I declared startDate as type java.utilDate, and I also have getters and setters. From the startDate database, the date type.

When I get the default format and I format the date

SimpleDateFormat df = new SimpleDateFormat(" dd MMM yyyy"); Date oneDate = new Date(startDate); df.format(oneDate); 

The problem I am facing is df.format(oneDate); returns a String. Is it possible to convert df.format(oneDate) back to Date, so I do not need to change my startDate data type.

Any help is appreciated.

thanks

+4
source share
4 answers

According to the comment on the issue:

@BalusC I agree with what you said is better to format in the user interface. So I added the following on the jsf page.

 <p:inputText value="#{vacationschedule.convertTime(vacationschedule.selectedRow.startDate)}"> 

and convertTime in managedBean

 public String convertTime(Date time){ Date date = new Date(); Format format = new SimpleDateFormat("yyyy MM dd"); return format.format(date); } 

<p:inputText> displays correctly, however, if I would like to use <p:calendar> , then I get an error

SEVERE: java.lang.IllegalArgumentException: cannot format this object as date

You are looking for a solution in the wrong direction. Human-oriented formatting should be done on the view side (UI), not on the model side, not to mention the controller side.

To represent a Date object in a human-friendly template in a JSF component, you must use the <f:convertDateTime> provided by the standard JSF Component Set:

 <p:inputText value="#{vacationschedule.selectedRow.startDate}"> <f:convertDateTime pattern="yyyy MM dd" /> </p:inputText> 

That way you can keep the property of all Date all the time. This way, you can also save the edited value (which would not be possible on the first try!).

In relation to the <p:calendar> PrimeFaces component, it has the pattern attribute for this purpose:

 <p:calendar value="#{vacationschedule.selectedRow.startDate}" pattern="yyyy MM dd" /> 

Download and refer to the PrimeFaces User Guide for all available attributes.

+10
source

Using the same SimpleDateFormat object you created,

 df.parse(yourDateString); 
+2
source

I hope my code helps you

 public String dateToString(Date date, SimpleDateFormat formatter) { return formatter.format(date); } public Date stringToDate(String date, SimpleDateFormat formatter) { try { return formatter.parse(date); } catch (ParseException e) { //Catching exception } return null; } 
0
source

This works for me:

 <p:calendar value="#{calTestBean.dateStr}" pattern="MM/dd/yyyy"> <f:convertDateTime pattern="MM/dd/yyyy"/> </p:calendar> 

Link: JSF 2.0 + Primefaces 2.x: bind string to calendar

0
source

Source: https://habr.com/ru/post/1398618/


All Articles