-1

I am developing a JSF and primefaces application. In my some.xhtml file where I put p: calendar tag and I want to set its default value as current date (format e.g:01-09-2014). I have written private Date startDate; in backing bean.

<p:calendar value="#{bean.startDate}">

When I don't write below code and just assign private Date startDate = Calendar.getInstance(); it gives me default value(MON Sep 1 00:00:00 EST 2014) but not in proper format (01-09-2014) which I really want. So my question is that how to set date in custom format (01-09-2014) and assign it to Date object private Date startDate = this.defaultDate(); (see below:) to get default value in clientside with this(01-09-2014) format.

I am using jdk 1.7.

private Date startDate = this.defaultDate();
private Date defaultDate() {
    Date defaultDate = null;
    try {
        DateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        defaultDate = sdf.parse(sdf.format(Calendar.getInstance().getTime()));
    } catch (Exception e) {
         e.printStackTrace();
    }
    return defaultDate;
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Mohsin AR
  • 2,998
  • 2
  • 24
  • 36

2 Answers2

-1

You are parsing the date correctly (kind of, see below) with the DateFormatter but not formatting it again for display:-

 sdf.format(defaultDate);

That is to say, when you output it:-

 System.out.println(sdf.format(defaultDate));

A Date object only holds an actual date, not information on how it should be formatted or which pieces of information contained in the Date to display (seconds, minutes, hours, day of week, day of month, month, year). Hence the use of DateFormatter to select only the parts you wish to display, in the order you wish to display them.

Additionally

When you are originally getting the date:-

defaultDate = sdf.parse(sdf.format(Calendar.getInstance().getTime()));

You are getting a Date object (with Calendar.getInstance().getTime()), converting it to a String using your DateFormatter (with sdf.format()) then using your DateFormatter to convert it back to a Date (with sdf.parse()) when you could just do:-

Date defaultDate = Calendar.getInstance().getTime();
Ross Drew
  • 8,163
  • 2
  • 41
  • 53
-1

you can use

DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String displayDate = dateFormat.format(new Date());

this will give you formatted date in the format dd-MM-yyyy as string

Prasad Khode
  • 6,602
  • 11
  • 44
  • 59