Reputation: 385
I want to implement following scenario: Get the Locale from my JSF-Page.
Now I want save the date format from the locale in my database.
Example:
locale = US
=> String dateformat = "YYYY-MM-dd"
But how can I get the correct Dateformat
from the Locale
?
The same thing should I need for:
Can anybody please give an example? I see already a library (jodaTime) But how can I do this?
Upvotes: 1
Views: 118
Reputation: 44061
First remark: There is in general no unique date or time format for any given locale since you have also to consider for example the precision issue i.e. style. For example in US you can write out "January" or "Jan" or a number instead (here again at least two variants either "01" or just "1").
Answer to question a): But there is indeed a way to extract common patterns for a given locale. Here the way for SimpleDateFormat
(JodaTime internally uses the same way):
static String getDateFormat(int style, Locale locale) {
DateFormat fmt = DateFormat.getDateInstance(style, locale);
if (fmt instanceof SimpleDateFormat) { // almost always true
return ((SimpleDateFormat) fmt).toPattern();
} else {
throw new UnsupportedOperationException("Cannot get date pattern for: " + locale);
}
}
public static void main(String... args) {
System.out.println(getDateFormat(DateFormat.SHORT, Locale.US);
// Output: M/d/yy
}
Answer to question b): To get a time pattern is very similar, just study the javadoc of java.text.DateFormat, there especially the method getTimeInstance(int, Locale)
Answer to question c): The time zone concept has nothing to do with localization. For example US or Russia have several time zones. And in reverse, at least conceptually, the IANA-TZDB does not exclude to have several locales in one time zone. For example "Europe/San_Marino" is just a link/alias for/to "Europe/Rome", that is, not an independent time zone identifier with its own data. But at least for the purpose of helping users to select the right time zone, the IANA-TZDB offers this lookup table which is built into all distributions of tzdb:
https://github.com/eggert/tz/blob/master/zone.tab
Unfortunately Java does not offer a standard API access for this table, not even the new JSR-310 (java.time.* in Java 8) or Joda-Time so it is up to you to evaluate the zone.tab-table yourself. It might be a better way for you to get the right time zone directly from user based on his/her preferences. For example in a web-based scenario JavaScript offers solutions to extract this information and then send it to the server where it can be processed by your Java program. See this SO-answer.
Upvotes: 1