Can not retrieve date from JDateChooser in Java

iOSAppDev picture iOSAppDev · Jul 20, 2011 · Viewed 24k times · Source

I am using JDateChooser from here

However I can not retrieve the date in format set with the method setDateFormatString while displaying it in console.

enter image description here

In first label shows actual date retrieved from JDateChooser while second label shows the format which I have set. When I select date from JDateChooser I get the date as 22-07-2011 as shown in image. But when I use getDate method, it will give me date as Fri Jul 22 00:00:00 GMT+05:30 2011. I want only 22-07-2011.

Here is my code. I am using Netbeans IDE 7.0

public JDateChooser() {
    initComponents();
    dateChooser.setDateFormatString("dd-MM-yyyy");
}
private void btnDisplayDateActionPerformed(java.awt.event.ActionEvent evt) {
    String dateFromDateChooser = dateChooser.getDate().toString();
    lblDate.setText(dateFromDateChooser);
    lblDateFormat.setText(dateChooser.getDateFormatString().toString());
    System.out.println(dateFromDateChooser);
}
public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            new JDateChooser().setVisible(true);
        }
    });
}

Answer

Kainsin picture Kainsin · Jul 20, 2011

You can use the String.format method to get the desired result.

Date dateFromDateChooser = dateChooser.getDate();
String dateString = String.format("%1$td-%1$tm-%1$tY", dateFromDateChooser);