Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get localized date pattern string?

It is quite easy to format and parse Java Date (or Calendar) classes using instances of DateFormat.

I could format the current date into a short localized date like this:

DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()); String today = formatter.format(new Date()); 

My problem is that I need to obtain this localized pattern string (something like "MM/dd/yy").

This should be a trivial task, but I just couldn't find the provider.

like image 885
Paweł Dyda Avatar asked Jan 04 '11 14:01

Paweł Dyda


People also ask

How do I get a locale date?

Use the toLocaleString() method to get a date and time in the user's locale format, e.g. date. toLocaleString() . The toLocaleString method returns a string representing the given date according to language-specific conventions.

How do I print local date?

LocalDate. The LocalDate. now() method returns the instance of the LocalDate class. If we print the instance of the LocalDate class, it prints the current date.

How do you localize a date in Java?

Java SimpleDateFormat with Locale String pattern = "EEEEE MMMMM yyyy HH:mm:ss. SSSZ"; SimpleDateFormat simpleDateFormat =new SimpleDateFormat(pattern, new Locale("fr", "FR")); String date = simpleDateFormat. format(new Date()); System.


2 Answers

For SimpleDateFormat, You call toLocalizedPattern()

EDIT:

For Java 8 users:

The Java 8 Date Time API is similar to Joda-time. To gain a localized pattern we can use class DateTimeFormatter

DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);

Note that when you call toString() on LocalDate, you will get date in format ISO-8601

Note that Date Time API in Java 8 is inspired by Joda Time and most solution can be based on questions related to time.

like image 113
Damian Leszczyński - Vash Avatar answered Sep 30 '22 13:09

Damian Leszczyński - Vash


For those still using Java 7 and older:

You can use something like this:

DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()); String pattern       = ((SimpleDateFormat)formatter).toPattern(); String localPattern  = ((SimpleDateFormat)formatter).toLocalizedPattern(); 

Since the DateFormat returned From getDateInstance() is instance of SimpleDateFormat. Those two methods should really be in the DateFormat too for this to be less hacky, but they currently are not.

like image 24
Zarremgregarrok Avatar answered Sep 30 '22 15:09

Zarremgregarrok