1

hello guys I've been on this issue for 4 hours and I don't seem able to solve it. I want the date selected using JDateChooser to be converted to this format dd-mm-yyyy but I couldn't do this. This what I wrote but it prints the date as :Thu Aug 21 00:00:00 WEST 2014. I want it to be printed 21-08-2014 This is my code:

public void addIns() {
    JTextField ch=(JTextField) dateChooser.getDateEditor().getUiComponent();
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
    try{
        Date date = df.parse(ch.getText());
        } catch(Exception e){System.out.println("wrong date");}
      System.out.println(date);   }
Abdelaziz Dabebi
  • 1,624
  • 1
  • 16
  • 21
  • possible duplicate of [Format date in java](http://stackoverflow.com/questions/4772425/format-date-in-java) – JonK Aug 09 '14 at 22:33

1 Answers1

2

The format Thu Aug 21 00:00:00 WEST 2014 is the default format of the Date.toString method.

So, if you are expecting:

System.out.println(date);

To print 21-08-2014, then you are wrong.

You could:

  • in Java 8 use LocalDate and LocalTime, and have a decent toString (but that won't print 21-08-2014).
  • print the date with the format method, eg: df.format(date);

And, since you are using Swing - and Swing components - there is probably a better way to get or set the format on the component.

NoDataFound
  • 11,381
  • 33
  • 59