Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primefaces Calendar component & date conversions

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.

  1. Is anything incorrect with f:convertDateTime tag written above.
  2. If not, how can I convert this string to sql date. Not able to understand what format should be given.

Thanks, Shikha

like image 599
Shikha Dhawan Avatar asked Dec 04 '22 16:12

Shikha Dhawan


2 Answers

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);
like image 60
Daniel Avatar answered Feb 16 '23 04:02

Daniel


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());
}
like image 33
Matt Handy Avatar answered Feb 16 '23 03:02

Matt Handy