juiceb0xk
juiceb0xk

Reputation: 969

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.

Upvotes: 2

Views: 11458

Answers (3)

Use this simple code:

  bill_date.setDateFormatString("yyyy-MM-dd");

In here bill_date is instance of the JDateChooser.

Upvotes: 0

You are printing the date but no using the formatter, you need to do:

String pattern  = "dd-MM-yyyy";
DateFormat formatter = new SimpleDateFormat(pattern);
System.out.println(formatter.format(newDate));

edit:

if your goal output is: 02/12/2016 then in the pattern in the format incorrect, you will need to use slash and not hyphens

use instead dd/mm/yyyy

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201439

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));

Upvotes: 1

Related Questions