Progress28.ru

IT Новости


09ae9cb0
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Locale english java

SimpleDateFormat and locale based format string

I’m trying to format a date in Java in different ways based on the given locale. For instance I want English users to see «Nov 1, 2009» (formatted by «MMM d, yyyy») and Norwegian users to see «1. nov. 2009» («d. MMM. yyyy»).

The month part works OK if I add the locale to the SimpleDateFormat constructor, but what about the rest?

I was hoping I could add format strings paired with locales to SimpleDateFormat, but I can’t find any way to do this. Is it possible or do I need to let my code check the locale and add the corresponding format string?

9 Answers 9

Use DateFormat.getDateInstance(int style, Locale locale) instead of creating your own patterns with SimpleDateFormat .

Use the style + locale: DateFormat.getDateInstance(int style, Locale locale)

Run the following example to see the differences:

The troublesome classes of java.util.Date and SimpleDateFormat are now legacy, supplanted by the java.time classes.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

DateTimeFormatter

Use DateTimeFormatter to generate strings representing only the date-portion or the time-portion.

To localize, specify:

  • FormatStyle to determine how long or abbreviated should the string be.
  • Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.

Going the other direction, you can parse a localized string.

Note that the locale and time zone are completely orthogonal issues. You can have a Montréal moment presented in Japanese language or an Auckland New Zealand moment presented in Hindi language.

Another example: Change 6 junio 2012 (Spanish) to 2012-06-06 (standard ISO 8601 format). The java.time classes use ISO 8601 formats by default for parsing/generating strings.

Peruse formats

Here is some example code for perusing the results of multiple formats in multiple locales, automatically localized.

An EnumSet is an implementation of Set , highly optimized for both low memory usage and fast execution speed when collecting Enum objects. So, EnumSet.allOf( FormatStyle.class ) gives us a collection of all four of the FormatStyle enum objects to loop. For more info, see Oracle Tutorial on enum types.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Класс Java.util.GregorianCalendar в Java

GregorianCalendar — это конкретный подкласс (тот, который имеет реализацию всех своих унаследованных членов либо из интерфейса, либо из абстрактного класса) Календаря, который реализует наиболее широко используемый григорианский календарь, с которым мы знакомы.

java.util.GregorianCalendar против java.util.Calendar

Основное различие между классами GregorianCalendar и Calendar заключается в том, что класс Calendar, являющийся абстрактным классом, не может быть создан. Таким образом, объект класса Calendar инициализируется как:

Здесь объект с именем cal из класса календаря инициализируется с текущей датой и временем в локали по умолчанию и часовом поясе. Принимая во внимание, что класс GregorianCalendar, являющийся конкретным классом, может быть создан. Таким образом, объект класса GregorianCalendar инициализируется как:

Здесь объект с именем gcal класса GregorianCalendar инициализируется с текущей датой и временем в локали и часовом поясе по умолчанию.

Читать еще:  Stringbuilder java методы

Поля определены:

Конструкторы: существует несколько конструкторов для объектов GregorianCalendar . В широком смысле, конструкторы для GregorianCalendar либо инициализируют объект с указанной пользователем датой и / или временем в локали и часовом поясе по умолчанию , либо инициализируют объект с датой и временем по умолчанию в указанной локали и / или часовом поясе пользователя . Это следующие:

Constructor SignatureDescription
GregorianCalendar()initializes the object with the current date and time in the default locale and time zone
GregorianCalendar(int year, int month, int dayOfMonth)initializes the object with the date-set passed as parameters in the default locale and time zone
GregorianCalendar(int year, int month, int dayOfMonth, int hours, int minutes)initializes the object with the date and time-set passed as parameters in the default locale and time zone
GregorianCalendar(int year, int month, int dayOfMonth, int hours, int minutes, int seconds)initializes the object with the date and more specific time-set passed as parameters in the default locale and time zone
GregorianCalendar(Locale locale)initializes the object with the current date and time in the default time zone and the locale passed as parameters
GregorianCalendar(TimeZone timeZone)initializes the object with the current date and time in the default locale and the time zone passed as parameters
GregorianCalendar(TimeZone timeZone, Locale locale)initializes the object with the current date and time in the locale and the time zone passed as parameters

Методы from () , toZonedDateTime () , getCalendarType () были введены в JDK 8.

// Java-программа для отображения этого класса календаря с
// экземпляр по умолчанию и класс GregorianCalendar
// конструктор по умолчанию в основном совпадает с
// возвращаем григорианский календарь по умолчанию
// дата, время, часовой пояс и локаль

public static void main(String[] args)

// Создание объекта класса Calendar

Calendar cal = Calendar.getInstance();

GregorianCalendar gcal = new GregorianCalendar();

/ * Отображение текущей даты с использованием

System.out.println( «Calendar date: «

/ * Отображение текущей даты с использованием

System.out.print( «Gregorian date: «

> // конец основной функции

Выход:

Пример для демонстрации использования различных конструкторов:
1. Использование конструктора по умолчанию

// Java-программа для демонстрации простого GregorianCalendar
// операции

public class GregorianCalendarGFG <

public static void main(String args[])

// объявляем массив для хранения сокращений месяцев

«May» , «Jun» , «Jul» , «Aug» ,

«Sep» , «Oct» , «Nov» , «Dec» >;

// объявляем массив для хранения AM или PM

/ * Создание объекта класса GregorianCalendar

используя конструктор по умолчанию * /

GregorianCalendar gcal = new GregorianCalendar();

// отображение даты, времени, часового пояса и локали

+ «Time Zone: » + gcal.getTimeZone().getDisplayName()

> // конец основной функции

Выход:

2. Передавая год, месяц, день месяца как параметры:

// Java-программа для демонстрации простого GregorianCalendar
// операции

public class GregorianCalendarGFG <

public static void main(String args[])

// объявляем массив для хранения сокращений месяцев

«May» , «Jun» , «Jul» , «Aug» ,

«Sep» , «Oct» , «Nov» , «Dec» >;

// объявляем массив для хранения AM или PM

/ * Создание объекта класса GregorianCalendar

указав год, месяц и день месяца * /

GregorianCalendar gcal = new GregorianCalendar( 2018 , 3 , 30 );

// отображение даты, времени, часового пояса и локали

+ «Time Zone: » + gcal.getTimeZone().getDisplayName()

> // конец основной функции

Выход:

3. Через год, месяц, день месяца, час дня, минуты:

// Java-программа для демонстрации простого GregorianCalendar
// операции

public class GregorianCalendarGFG <

public static void main(String args[])

// объявляем массив для хранения сокращений месяцев

«May» , «Jun» , «Jul» , «Aug» ,

«Sep» , «Oct» , «Nov» , «Dec» >;

// объявляем массив для хранения AM или PM

/ * Создание объекта класса GregorianCalendar

указав год, месяц, день месяца,

hourOfDay и минуты * /

GregorianCalendar gcal = new GregorianCalendar( 2018 , 3 , 30 , 10 , 21 );

// отображение даты, времени, часового пояса и локали

+ «Time Zone: » + gcal.getTimeZone().getDisplayName()

> // конец основной функции

Выход:

4. Через год, месяц, день месяца, час дня, минуты, секунды:

// Java-программа для демонстрации простого GregorianCalendar
// операции

public class GregorianCalendarGFG <

public static void main(String args[])

// объявляем массив для хранения сокращений месяцев

«May» , «Jun» , «Jul» , «Aug» ,

«Sep» , «Oct» , «Nov» , «Dec» >;

// объявляем массив для хранения AM или PM

/ * Создание объекта класса GregorianCalendar

указав год, месяц, день месяца,

hourOfDay, минуты и секунды * /

GregorianCalendar gcal = new GregorianCalendar( 2018 , 3 , 30 , 10 , 21 , 51 );

// отображение даты, времени, часового пояса и локали

+ «Time Zone: » + gcal.getTimeZone().getDisplayName()

> // конец основной функции

Выход:

5. Передав timeZone в качестве параметра:

// Java-программа для демонстрации простого GregorianCalendar
// операции

public class GregorianCalendarTest <

public static void main(String args[])

// объявляем массив для хранения сокращений месяцев

«May» , «Jun» , «Jul» , «Aug» ,

«Sep» , «Oct» , «Nov» , «Dec» >;

// объявляем массив для хранения AM или PM

/ * Создание объекта класса TimeZone для создания

объект класса GregorianCalendar для назначения

пользовательский часовой пояс (GMT + 5:30) * /

TimeZone tz = TimeZone.getTimeZone( «GMT+5:30» );

GregorianCalendar gcal = new GregorianCalendar(tz);

// отображение даты, времени, часового пояса и локали

+ «Time Zone: » + gcal.getTimeZone().getDisplayName()

> // конец основной функции

Выход:

6. Передав локаль в качестве параметра:

// Java-программа для демонстрации простого GregorianCalendar
// операции

public class GregorianCalendarTest <

public static void main(String args[])

// объявляем массив для хранения сокращений месяцев

«May» , «Jun» , «Jul» , «Aug» ,

«Sep» , «Oct» , «Nov» , «Dec» >;

// объявляем массив для хранения AM или PM

/ * Создание объекта класса Locale для создания

объект класса GregorianCalendar для назначения

пользовательская локаль (Индия) * /

Locale l = new Locale( «en» , «IN» );

GregorianCalendar gcal = new GregorianCalendar(l);

// отображение даты, времени, часового пояса и локали

java.util.Locale Example

Posted by: Rohit Joshi in Locale June 3rd, 2014 1 Comment Views

In this article we will discuss about the Locale class from java.util package. The Locale is used to make the system relevant and usable for the users from different cultures. In other words, it is used to customize the system for different people of different region, culture and language.

A Locale object represents a specific geographical, political, or cultural region.

Let’s discuss about the Locale class and how to create, query and use a Locale object.

1. Locale Instantiation

There are many ways to create a Locale object. As of JDK 7, there are four ways to create a Locale object. In the following example, we will see different ways of creating it and differences between them.

1.1 Using constructor

1.1a. Locale(String language) : Construct a locale from a language code. For e.g. “fr” is a language code for French.

1.1.b. Locale(String language, String country) : When you have a language code and a country, you can use this constructor with two parameters that takes a language as first parameter and a country as second parameter to create a locale object.

1.1c. Locale(String language, String country, String variant) : Construct a locale from language, country and variant. Any arbitrary value can be used to indicate a variation of a Locale .

1.2 Using Builder method

From JDK 7 releases, the Locale provides a Builder to create an instance of the Locale class. Using Locale.Builder you can instantiate an object that conforms to BCP 47 syntax.

Locale localeFromBuilder = new Locale.Builder().setLanguage(«en»).setRegion(«GB»).build();

1.3 Using forLanguageTag method:

forLanguageTag (String languageTag) returns a locale for the specified IETF BCP 47 language tag string. If the specified language tag contains any ill-formed subtags, the first such subtag and all the following subtags are ignored.

Locale forLangLocale = Locale.forLanguageTag(«en-GB»);

1.4 Locale constants

Java provides a set of pre-defined constants for some languages and countries. If a language constant is specified, then the regional portion of that locale is undefined.

Locale localeCosnt = Locale.FRANCE;

  • If we run the above code, we will have the following results:

Although, you can use any of these ways to create a locale object. But it is recommended to use forLanguageTag and Locale.Builder methods. The reason is these two methods return a locale for the specified IETF BCP 47 language tag string. BCP 47 imposes syntax restrictions that are not imposed by Locale’s constructors. This means that conversions between some Locales and BCP 47 language tags cannot be made without losing information.

2. Methods

In this section, we will discuss about some of the important methods of the Locale class. You can use these methods on a locale object to get some information about the Locale .

  • If we run the above code, we will have the following results:

Please note that in the above example, we have printed only that script and variant which are specified for the locale object.

Locale.getDefault() gets the current value of the default locale for current instance of the Java Virtual Machine. The Java Virtual Machine sets the default locale during startup based on the host environment.

Locale.getAvailableLocales() returns an array of all available locales installed on that particular JVM machine.

String getDisplayName() is an instance method which returns the name of the locale object (appropriate to display) in string form. The name contains values returned by getDisplayLanguage(), getDisplayScript(),getDisplayCountry(), and getDisplayVariant() methods .

String getLanguage() returns the language code of the locale object.

String getDisplayLanguage() returns the name of the locale’s language. It shows an appropriate name for display to the user.

String getCountry() returns the country/region code for this locale, which should either be the empty string, an uppercase ISO 3166 2-letter code, or a UN M.49 3-digit code.

String getDisplayCountry() returns the name of the locale’s country. It shows an appropriate name for display to the user.

String getScript() returns the script code for this locale. It should either be the empty string or an ISO 15924 4-letter script code. The first letter is uppercase and the rest are lowercase, for example, ‘Latn’, ‘Cyrl’.

String getDisplayScript() returns the name of the locale’s script appropriate for display to the user.

String getVariant() returns the variant code, or the empty string if none is defined.

String getDisplayVariant() returns a name for the locale’s variant code that is appropriate for display to the user.

3. Locale sensitive classes

The Locale is the mechanism for identifying the kind of object that you would like to get. Java provides certain classes which provide locale specific operations. For example, they provide methods to format values that represent dates, currency and numbers according to a specific locale. These classes are known as Locale sensitive classes.

In the following example, we will use NumberFormat , Currency , and DateFormat classes to illustrate about locale sensitive operations.

  • If we run the above code, we will have the following results:

In the above example, we have used the getInstance() static method to get the instance about the respective class. The getInstance() methods used in two variety one without locale (which uses the default locale set in the current instance of the JVM) and another with a Locale as its parameter.

You can clearly see the differences in the output due to difference in the locale object used.

This was an example of how to use the Locale class and some of its basic methods.

Ссылка на основную публикацию