javastringdatesimpledateformatjdatechooser

How do I format JDateChooser into dd-mm-yyyy?


I am trying to output the current date format into:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");, but it is outputting like this:

Fri Dec 02 14:03:59 AEST 2016

Here is my code:

JDateChooser datePurchased = new JDateChooser();
DateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
Date newDate = new Date();
datePurchased.setDate(newDate);

I am now printing the result like this:

System.out.println(newDate.toString());

But this does not print out what I want, as per above.

My goal output is: 02/12/2016, how do I go about doing this, I've tried looking around but I cannot find the likes to solve my problem.

Thank you in advance.


Solution

  • The first part is simple enough, a Date is a representation in epoch time and doesn't have a modifiable format. Instead, you format it when you want to display it (or otherwise obtain a String representation). Additionally, you need M for months (m is minutes) and if you want / use that instead of -. For example,

    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    Date newDate = new Date();
    System.out.println(dateFormat.format(newDate));