How can I set the global default date format in Java?
Is there a way to set the default DateFormat class used for parsing strings into dates?
My background: I开发者_StackOverflow get exceptions reading date values from JDBC because the date string is not in the expected format.
(text added on 2011-07-22):
Seems I need to precise my question description: I use a foreign, proprietary database together with a proprietary JDBC driver. There is no possibility to know or even change the column type on database side. When I try to read the ResultSet columns via ResultSet.getDate() or ResultSet.getObject() some exception is triggered inside the JDBC driver like "10 Jul 1999 is not a valid date". What I want to achieve is to avoid this internal exception by setting some appropriate global default date format. Maybe I would need to implement some custom Locale first and the install that Locale globally?
There should be totally no need for this.
Dates should be stored in DB as a DATE
, DATETIME
or TIMESTAMP
field, depending on the DB used and the information you'd like to store (e.g. date only or date and time combined), not as a VARCHAR
or something. Such a date-specific field stores the value under the covers basically as an integer/long with the epoch time as value.
Assuming that you're using a date+time field type such as DATETIME
or TIMESTAMP
, then you should be saving it in the DB using PreparedStatement#setTimestamp()
. Here's an example, assuming that the date
variable is of a java.util.Date
type:
preparedStatement.setTimestamp(1, new Timestamp(date.getTime()));
And you should be retrieving them from the DB using ResultSet#getTimestamp()
which returns a Timestamp
which in turn is a subclass of java.util.Date
, so you could just safely upcast it:
Date date = resultSet.getTimestamp("columnname");
As to parsing/formatting the java.util.Date
object from/into a human readable String
format, this should technically happen in the view side, not in the persistence layer. How exactly to do this in turn depends on the view/UI technology/framework used, such as Swing, JSP, JSF, Struts2, Spring-MVC, etcetera. As it's not clear from your question which one you're using, it's not possible to give a suitable answer. In general, they all use SimpleDateFormat
API under the covers. You could even use it in raw form.
You can set your default Locale:
Locale.setDefault(Locale.US);
Alternatively, you can use one of the DateFormat
static methods which accepts a Locale to just get the format for the Locale you're interested in. If your date format doesn't match one of the standard ones, you'll need to create your own SimpleDateFormat
(based on a pattern) and make sure you always use that one instead of the default one.
精彩评论