2

I'd like to insert the value derived from this JXDatePicker into a Date field in Java DB. How should I get ONLY date off this controller in a way that time is represented as dd/mm/yyyy and nothing else??!

Jonathan Spooner
  • 7,682
  • 2
  • 34
  • 41
Sam
  • 2,702
  • 5
  • 31
  • 45

1 Answers1

6

You can get the Date from the JXDatePicker.getDate() and then use a SimpleDateFormat to format the date into the required format.

Try:

SimpleDateFormat formater = new SimpleDateFormat("dd/MM/yyyy");
formater.format(myDatePicker.getDate());

Notice that instead of the mm that you've used I used MM to represent the month. Please see the SimpleDateFormat javadoc for pattern letters you can use.

Follow-Up

I feel compelled to mention, for completeness, that it is generally a bad idea to put formatted strings representing dates into a database; what happens when you want to display it in another format, for instance, or do a simple comparison using SQL.

One way to store date/times is to use the timestamp that you get from Date.getTime(). Here's the Date class' getTime() javadoc:

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

Storing this representation of a Date in your database makes it much simpler to create a Date object when you retrieve the timestamp:

Long myTimeStamp = getTimeStampFromResultSet();
Date date = new Date(myTimeStamp);

Or use the column in SQL to do a simple comparison:

SELECT * FROM MY_TABLE WHERE MY_DATE > ?

It also makes it somewhat portable so you can, for instance, send the timestamp to a thin client that is built using a different technology.

That being said, it is also in your best interest to use a date and time library like Joda Time instead of using the unreliable and inconvenient Java Date or Calendar classes.

Jonathan Spooner
  • 7,682
  • 2
  • 34
  • 41