blackHorsie
blackHorsie

Reputation: 127

Displaying date in JTextField while User enters numbers (Java)

I'm a begginner in programming and I have simple program, which calculates something, using dates in the calculation formula.

So, I have two fields:

JTextField startDate - for entering first date, and JTextField endDate - for second date.

When user enters any values to that fields, I'm using getText() and then these values are converted to SimpleDateFormat DATE = new SimpleDateFormat("ddMMyyyy") by using DATE.parse("value from getText()"). After that we can do with our new Date value whatever we want.

What is the problem and what I want to do. The date input looks like:

enter image description here

But visually it's not good for me. I want to do some kind of "auto date input". For example: user enters "09052017", but in the JTextField we see "09.05.2017", or user just enters "09", but in the field we see "09.", then "0905", but in the field we have "09.05.". So, the user enters 09052017, but in the field we see:

enter image description here

How to realize that?

Upvotes: 0

Views: 809

Answers (2)

Eradicator_1729
Eradicator_1729

Reputation: 180

You can use SimpleDateFormat to format dates however you want. You have wildcards for the date parameters and then you can add separating characters like slashes or dots.

String pattern = "MM.dd.yyyy";
SimpleDateFormat sdf = new SimpleDateFormat (pattern);
String t = sdf.format (new Date());

Upvotes: 0

Yousaf
Yousaf

Reputation: 29281

Use JCalendar. It is like a small calendar which will open in you gui and user can select the desired date.

To use a JCalendar, you need to import a .jar file in your project that is provided in the link provided above.

JCalendar looks like

enter image description here

Additionally you can change the format of the date to whatever you want.

Upvotes: 2

Related Questions