Is it possible to get a date object formatted in Java?

advertisements

This question already has an answer here:

  • Format Date output in JSF 3 answers
     SimpleDateFormat formatter=
      new SimpleDateFormat("yyyy MMM dd");
     String dateNow = formatter.format(rs.getDate("ExpirationDate").getTime());
System.out.println("Date in String: "+dateNow);
     expDate = formatter.parse(dateNow);
System.out.println("expDate: "+expDate);

Here is the code through which I am trying to format the date to 2013 Apr 26 format.Now SimpleDateFormat#format method returns a formatted String but I need a java.util.Date object with desired format? Is it possible
Note: Actually I need the date object becuase I have to print it on my JSF page and when I tried to print it on JSF it shows defualt format of java.util.Date i-e Mon Mar 04 00:00:00 PKT 2013 whereas I want this 2013 Apr 26
Another thing is that I found a annotation is Spring framework which is @DateTimeFormat(pattern = "yyyy MMM dd") which works itself.Is there anything like this annotation in JSF 2.0.
Thanks


The Date class does not store any information about formatting. The Date class exist basically merely of a private long milliseconds field. The format which you're seeing when you're printing a Date instance is just its default toString() format which is clearly specified in its javadoc.

In JSF context, you need <f:convertDateTime> tag to convert between Date in model and String in HTML/HTTP. This can be used in both UIOutput and UIInput components.

<h:outputText value="#{bean.date}">
    <f:convertDateTime pattern="yyyy MMM dd" />
</h:outputText>
...
<h:inputText value="#{bean.date}">
    <f:convertDateTime pattern="dd-MM-yyyy" />
</h:inputText>