I am using primefaces' calendar component. I have a corresponding string in VO. While saving in database, I need to convert the string to java.sql.date.
xhtml:
<p:calendar value="#{articlePromo.startDate}"
id="vendorStartDateInputTxt" pattern="dd/MM/yyyy" mode="popup" showOn="button">
<f:convertDateTime type="date" dateStyle="short" pattern="dd/MM/yyyy" />
</p:calendar>
The startDate (String) has the value : Sat Apr 21 05:30:00 IST 2012
Java method to get sql Date
public static Date getSQLDate(String strDate) {
java.sql.Date sqlDate = null;
try {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date dt = formatter.parse(strDate);
sqlDate = new java.sql.Date(dt.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return sqlDate;
}
While converting java.util.date of calendar, I used the pattern dd/MM/yyyy. But the date it got converted to is: Sat Apr 21 05:30:00 IST 2012.
Thanks, Shikha
try
<p:calendar value="#{articlePromo.startDate}"
id="vendorStartDateInputTxt" pattern="dd/MM/yyyy" mode="popup" showOn="button">
</p:calendar>
where startDate
is java.util.Date
object
Also, if you want to format the Date Object you can use the SimpleDateFormat :
DateFormat df=new SimpleDateFormat("dd/MM/yyyy");
String s=df.format(startDate);
The f:convertDateTime
only converts String to Object and vice versa. The Object for the p:calendar
needs to be a java.util.Date
(it is the value
attribute). The String is the formatted date that you see in the browser!
The Primefaces calendar automatically attaches a converter. That's why you have the pattern
attribute in p:calendar
.
So you should remove your additional f:convertDateTime
as already proposed by Daniel.
Then the conversion from java.util.Date
to java.sql.Date
is quite simple:
public java.sql.Date sqlDate(java.util.Date calendarDate) {
return new java.sql.Date(calendarDate.getTime());
}
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