0
     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

4

3 回答 3

3

该类Date不存储有关格式的任何信息。该类Date基本上仅存在于一个private long milliseconds领域。您在打印Date实例时看到的格式只是其默认格式,在其 javadoctoString()中明确指定。

在 JSF 上下文中,您需要标签在模型和HTML/HTTP<f:convertDateTime>之间进行转换。这可以在和组件中使用。DateStringUIOutputUIInput

<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>
于 2013-04-24T11:17:37.907 回答
2

没有格式化的 Date 对象之类的东西。除了在其 toString 方法中使用的格式之外,日期对象没有任何内在格式。您需要使用日期格式以特定方式格式化它们,就像您在问题中所做的那样。

于 2013-04-24T06:30:27.603 回答
1

你可以这样做:

public class MyDate extends Date{

    public String toString(){
        SimpleDateFormat formatter= 
        new SimpleDateFormat("yyyy MMM dd");
        String dateNow = formatter.format(this.getTime());
        String ans="";
        ans+="Date in String: "+dateNow;
        expDate = formatter.parse(dateNow);
        ans+="\n"+"expDate: "+expDate;
        return ans;
    }    
}

有了这个,您可以使用 MyDate ,它将根据需要打印。

System.out.println(new MyDate());
于 2013-04-24T07:04:40.550 回答