Java I18n 简明教程

Java Internationalization - Quick Guide

Java Internationalization - Overview

国际化或 I18N是指应用程序能够用多种不同语言为用户提供服务的功能。Java 对国际化具有内置支持。Java 还提供数字、货币的格式化以及相应地调整日期和时间。

Internationalization or I18N refers to the capability of an Application to be able to serve users in multiple and different languages. Java has in-built support for Internationalization. Java also provides formatting of numbers, currencies and adjustment of date and time accordingly.

Java 国际化有助于使 Java 应用程序处理不同的语言、数字格式、货币、特定区域时间格式化。

Java Internationalization helps to make a java application handle different languages, number formats, currencies, region specific time formatting.

Localization

本地化或 L10N是指应用程序的适应性,即应用程序如何适应特定语言、数字格式、日期和时间设置等。

Localization or L10N is the adaptability of an application that is how an application adapts itself with a specific language, number formats, date and time settings etc.

为了实现本地化,Java 应用程序应实现国际化。

A java application should be internationalized in order to be able to localize itself.

Culturally Dependent Information

以下信息项通常随不同时区或文化而变化。

Following information items often varies with different time zones or cultures.

  1. Messages

  2. Date

  3. Time

  4. Number

  5. Currency

  6. Measurements

  7. Phone Numbers

  8. Postal Addresses

  9. GUI labels

Internationalization Classes

Java 有一组内置类可帮助应用程序实现国际化。这些类如下所示:

Java has a set of built-in classes which help in internationalization of an application. These classes are following:

Sr.No.

Class & Description

1

Locale Represents a language along with country/region.

2

ResourceBundle Contains localized text or objects.

3

NumberFormat Use to format numbers/currencies as per the locale.

4

DecimalFormat Use to format numbers as per customized format and as per locale.

5

DateFormat Use to format dates as per locale.

6

SimpleDateFormat Use to format dates as per customized format and as per locale.

Java Internationalization - Environment Setup

在本章,我们将讨论为 Java 设置宜人环境的事物的不同方面。

In this chapter, we will discuss on the different aspects of setting up a congenial environment for Java.

Local Environment Setup

如果您仍然希望为 Java 编程语言设置您的环境,本文将指导您如何在您的机器上下载和设置 Java。以下是设置环境的步骤。

If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Following are the steps to set up the environment.

Java SE 可以通过链接 Download Java 免费获得。您可以根据您的操作系统下载一个版本。

Java SE is freely available from the link Download Java. You can download a version based on your operating system.

按照说明下载 Java 并运行 .exe 以在您的机器上安装 Java。一旦您在您的机器上安装了 Java,您将需要设置环境变量来指向正确的安装目录 −

Follow the instructions to download Java and run the .exe to install Java on your machine. Once you installed Java on your machine, you will need to set environment variables to point to correct installation directories −

Setting Up the Path for Windows

假设你已将 Java 安装在 c:\Program Files\java\jdk 目录中 −

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  1. Right-click on 'My Computer' and select 'Properties'.

  2. Click the 'Environment variables' button under the 'Advanced' tab.

  3. Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

Setting Up the Path for Linux, UNIX, Solaris, FreeBSD

应该设置环境变量 PATH 以指向已安装 Java 二进制文件的位置。如果您遇到困难,请参阅您的 shell 文档。

Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation, if you have trouble doing this.

例如,如果您使用 bash 作为您的 shell,那么您将向 '.bashrc 的尾部添加以下行: export PATH = /path/to/java:$PATH'

Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH = /path/to/java:$PATH'

要编写 Java 程序,您将需要一个文本编辑器。市场上有更复杂的 IDE。但现在,您可以考虑以下内容之一 −

To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following −

  1. Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.

  2. Netbeans − A Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html.

  3. Eclipse − A Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/.

What is Next?

下一章将教你如何编写和运行你的第一个 Java 程序以及开发应用程序所需的一些重要的 Java 基本语法。

Next chapter will teach you how to write and run your first Java program and some of the important basic syntaxes in Java needed for developing applications.

Java Internationalization - Locale Class

Locale 对象表示特定的地理/政治/文化区域。需要 Locale 来执行其任务的任何操作称为区域敏感操作,并使用 Locale 来掌握与用户相关的信息。例如,显示数字就是区域敏感操作。该数字应按照用户所在国家、地区或文化的习俗和惯例进行格式化。

A Locale object represents a specific geographical/political/cultural region. Any operation requiring a Locale to perform its task is called locale-sensitive operation and uses the Locale to master information relative to the user. For example, displaying a number is a locale-sensitive operation. The number should be formatted as per the customs and conventions of the user’s native country, region, or culture.

Locale Contents

Locale 对象包含以下内容:

A Locale object contains the following:

  1. Language - ISO 639 alpha-2 or alpha-3 language code, or registered language subtags up to 8 alpha letters. alpha-2 code must be used if both alpha-2 and alpha-3 code are present. The language field is case insensitive, but Locale always canonicalizes to lower case.

  2. Script - ISO 15924 alpha-4 script code. The script field is case insensitive, but Locale always canonicalizes to title case.

  3. Country (region) - ISO 3166 alpha-2 country code or UN M.49 numeric-3 area code. The country field is case insensitive, but Locale always canonicalizes to upper case.

  4. Variant - Any arbitrary value used to indicate a variation of a Locale. Where there are two or more variant values each indicating its own semantics, these values should be ordered by importance, with most important first, separated by underscore('_'). The variant field is case sensitive.

  5. Extensions - A map from single character keys to string values, indicating extensions apart from language identification. The extensions in Locale implement the semantics and syntax of BCP 47 extension subtags and private use subtags. The extensions are case insensitive, but Locale canonicalizes all extension keys and values to lower case.

Java Internationalization - Example - Locale Details

在此示例中,我们将获取默认语言环境并打印其详细信息。然后为“fr”创建语言环境并打印其详细信息。

In this example, we’ll get default locale and print its details. Then create a locale for "fr" and print its details.

Example

import java.util.Locale;

public class I18NTester {
   public static void main(String[] args) {
      Locale locale =Locale.getDefault();

      System.out.println("Default Locale Properties:\n");

      System.out.println(locale.getDisplayCountry());
      System.out.println(locale.getDisplayLanguage());
      System.out.println(locale.getDisplayName());
      System.out.println(locale.getISO3Country());
      System.out.println(locale.getISO3Language());
      System.out.println(locale.getLanguage());
      System.out.println(locale.getCountry());

      Locale frenchLocale = new Locale("fr","fr");

      System.out.println("\nfr Locale Properties:\n");
      System.out.println(frenchLocale.getDisplayCountry());
      System.out.println(frenchLocale.getDisplayLanguage());
      System.out.println(frenchLocale.getDisplayName());
      System.out.println(frenchLocale.getISO3Country());
      System.out.println(frenchLocale.getISO3Language());
      System.out.println(frenchLocale.getLanguage());
      System.out.println(frenchLocale.getCountry());
   }
}

Output

它将打印以下结果。

It will print the following result.

Default Locale Properties:

United States
English
English (United States)
USA
eng
en
US

fr Locale Properties:

France
French
French (France)
FRA
fra
fr
FR

Java Internationalization - Example - Display Language

在此示例中,我们将获取作为参数传递的语言每区域显示。

In this example, we’ll get display language per locale passed as an argument.

Example

import java.util.Locale;

public class I18NTester {
   public static void main(String[] args) {
      Locale defaultLocale = Locale.getDefault();
      Locale enLocale = new Locale("en", "US");
      Locale frLocale = new Locale("fr", "FR");
      Locale esLocale = new Locale("es", "ES");

      System.out.println(defaultLocale.getDisplayLanguage(enLocale));
      System.out.println(defaultLocale.getDisplayLanguage(frLocale));
      System.out.println(defaultLocale.getDisplayLanguage(esLocale));
   }
}

Output

它将打印以下结果。

It will print the following result.

English
anglais
inglés

Java Internationalization - ResourceBundle Class

ResourceBundle 类用于存储与语言环境相关的文本和对象。我们通常使用属性文件来存储特定语言环境的文本并使用 ResourceBundle 对象来表示它们。以下是 Java 中基于应用程序使用特定语言环境的属性文件的步骤。

ResourceBundle class is used to store text and objects which are locale sensitive. Generally we use property files to store locale specific text and then represent them using ResourceBundle object. Following are the steps to use locale specific properties file in a java based application.

Step 1: Create Properties Files.

假设我们需要英语语言环境的属性文件。然后创建一个属性文件名称为 XXX_en_US.properties,其中 XXX 是文件名称,而 en_US 表示英语 (美国) 的语言环境。

Suppose we need properties file for English locale. Then create a properties file name XXX_en_US.properties where XXX is the name of the file and en_US represents the locale for English(US).

Messages_en_US.properties

Messages_en_US.properties

message=Welcome to TutorialsPoint.COM!

现在,让我们为法语语言环境创建一个属性文件。然后创建一个名为 XXX_fr_FR.properties 的属性文件,其中 XXX 是文件名称,而 fr_FR 代表法语 (法国) 的语言环境。

Let’s now create properties file for French locale. Then create a properties file name XXX_fr_FR.properties where XXX is the name of the file and fr_FR represents the locale for French(France).

Messages_fr_FR.properties

Messages_fr_FR.properties

message=Bienvenue sur TutorialsPoint.COM!

在这里你可以发现键是相同的,但值在两个属性文件中属于特定语言环境。

Here you can figure out that the key is same but the value is locale specific in both the properties file.

Step 2: Create ResourceBundle Object

使用属性文件名称和语言环境通过以下语法创建 ResourceBundle 对象。

Create ResourceBundle object with properties file name and locale using following syntax.

ResourceBundle bundle = ResourceBundle.getBundle("Messages", Locale.US);

Step 3: Get the Value from ResourceBundle Object

通过传递键从 ResourceBundle 对象获取值。

Get the value from ResourceBundle object by passing the key.

String value = bundle.getString("message");

Example

以下示例说明如何使用 ResourceBundle 对象从属性文件中显示特定语言环境的值。

Following example illustrate the use of ResourceBundle objects to display locale specific values from properties files.

import java.util.Locale;
import java.util.ResourceBundle;

public class I18NTester {
   public static void main(String[] args) {
      ResourceBundle bundle = ResourceBundle.getBundle("Messages", Locale.US);
      System.out.println("Message in "+Locale.US +": "+bundle.getString("message"));

      bundle = ResourceBundle.getBundle("Messages", Locale.FRANCE);
      System.out.println("Message in "+Locale.FRANCE +": "+bundle.getString("message"));
   }
}

它将打印以下结果。

It will print the following result.

Message in en_US: Welcome to TutorialsPoint.COM!
Message in fr_FR: Bienvenue sur TutorialsPoint.COM!

Notes for Naming Conventions

以下是属性文件的命名约定。

Following are the naming conventions for the properties file.

  1. For properties file mapped to default locale, no prefix is mandatory. message_en_US.properties is equivalent to message.properties.

  2. For properties file mapped to locale, prefix can be attached in two ways. message_fr.properties is equivalent to message_fr_FR.properties.

Java Internationalization - NumberFormat Class

java.text.NumberFormat 类用于根据特定区域设置对数字和货币进行格式化。数字格式因国家/地区而异。例如,丹麦使用逗号将数字的小数部分与整数部分分隔开,而英国使用句点作为分隔符。

The java.text.NumberFormat class is used for formatting numbers and currencies as per a specific Locale. Number formats varies from country to country. For example, In Denmark fractions of a number are separated from the integer part using a comma whereas in England they use a dot as separator.

Example - Format Numbers

在此示例中,我们根据美国语言环境和丹麦语言环境格式化数字。

In this example, we’re formatting numbers based on US locale and Danish Locale.

import java.text.NumberFormat;
import java.util.Locale;

public class I18NTester {
   public static void main(String[] args) {
      Locale enLocale = new Locale("en", "US");
      Locale daLocale = new Locale("da", "DK");

      NumberFormat numberFormat = NumberFormat.getInstance(daLocale);

      System.out.println(numberFormat.format(100.76));

      numberFormat = NumberFormat.getInstance(enLocale);

      System.out.println(numberFormat.format(100.76));
   }
}

Output

它将打印以下结果。

It will print the following result.

100,76
100.76

Java Internationalization - Format Currencies

Example

在此示例中,我们将根据美国语言环境和丹麦语言环境格式化货币。

In this example, we’re formatting currencies based on US locale and Danish Locale.

import java.text.NumberFormat;
import java.util.Locale;

public class I18NTester {
   public static void main(String[] args) {
      Locale enLocale = new Locale("en", "US");
      Locale daLocale = new Locale("da", "DK");

      NumberFormat numberFormat = NumberFormat.getCurrencyInstance(daLocale);

      System.out.println(numberFormat.format(100.76));

      numberFormat = NumberFormat.getCurrencyInstance(enLocale);

      System.out.println(numberFormat.format(100.76));
   }
}

Output

它将打印以下结果。

It will print the following result.

kr 100,76
$100.76

Java Internationalization - Format Percentages

Example

在此示例中,我们按百分比格式设置数字。

In this example, we’re formatting numbers in percentage format.

import java.text.NumberFormat;
import java.util.Locale;

public class I18NTester {
   public static void main(String[] args) {
      Locale enLocale = new Locale("en", "US");

      NumberFormat numberFormat = NumberFormat.getPercentInstance(enLocale);

      System.out.println(numberFormat.format(0.76));
   }
}

Output

它将打印以下结果。

It will print the following result.

76%

Java Internationalization - Set Min/Max Precision

Example

在此示例中,我们为数字的整数部分和小数部分设置最小和小数位。

In this example, we’re setting min and max digits for both integer as well as fractional part of a number.

import java.text.NumberFormat;
import java.util.Locale;

public class I18NTester {
   public static void main(String[] args) {
      Locale enLocale = new Locale("en", "US");

      NumberFormat numberFormat = NumberFormat.getInstance(enLocale);
      numberFormat.setMinimumIntegerDigits(2);
      numberFormat.setMaximumIntegerDigits(3);

      numberFormat.setMinimumFractionDigits(2);
      numberFormat.setMaximumFractionDigits(3);

      System.out.println(numberFormat.format(12234.763443));
   }
}

Output

它将打印以下结果。

It will print the following result.

234.763

Java Internationalization - Set Rounding Mode

Example

在此示例中,我们展示了舍入模式。

In this example, we’re showcasing Rounding Mode.

import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Locale;

public class I18NTester {
   public static void main(String[] args) {
      Locale enLocale = new Locale("en", "US");

      NumberFormat numberFormat = NumberFormat.getInstance(enLocale);

      numberFormat.setMinimumFractionDigits(0);
      numberFormat.setMaximumFractionDigits(0);

      System.out.println(numberFormat.format(99.50));

      numberFormat.setRoundingMode(RoundingMode.HALF_DOWN);

      System.out.println(numberFormat.format(99.50));
   }
}

Output

它将打印以下结果。

It will print the following result.

100
99

Java Internationalization - Parsing Numbers

Example

在此示例中,我们展示了在不同语言环境中出现的数字的解析。

In this example, we’re showcasing parsing of number present in different locale.

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

public class I18NTester {
   public static void main(String[] args) throws ParseException {
      Locale enLocale = new Locale("en", "US");
      Locale daLocale = new Locale("da", "DK");

      NumberFormat numberFormat = NumberFormat.getInstance(daLocale);

      System.out.println(numberFormat.parse("100,76"));

      numberFormat = NumberFormat.getInstance(enLocale);

      System.out.println(numberFormat.parse("100,76"));
   }
}

Output

它将打印以下结果。

It will print the following result.

100.76
10076

Java Internationalization - DecimalFormat Class

java.text.DecimalFormat 类用于按照自定义格式和区域设置对数字进行格式化。

The java.text.DecimalFormat class is used for formatting numbers as per customized format and as per locale.

Example - Format Numbers

在此示例中,我们根据给定的模式格式化数字。

In this example, we’re formatting numbers based on a given pattern.

import java.text.DecimalFormat;

public class I18NTester {
   public static void main(String[] args) {
      String pattern = "####,####.##";
      double number = 123456789.123;

      DecimalFormat numberFormat = new DecimalFormat(pattern);

      System.out.println(number);

      System.out.println(numberFormat.format(number));
   }
}

Output

它将打印以下结果。

It will print the following result.

1.23456789123E8
1,2345,6789.12

Java Internationalization - Format Patterns

以下是格式化模式中字符的用法。

Followings is the use of characters in formatting patterns.

Sr.No.

Class & Description

1

0 To display 0 if less digits are present.

2

# To display digit ommitting leading zeroes.

3

. Decimal separator.

4

, Grouping separator.

5

E Mantissa and Exponent separator for exponential formats.

6

; Format separator.

7

- Negative number prefix.

8

% Shows number as percentage after multiplying with 100.

9

? Shows number as mille after multiplying with 1000.

10

X To mark character as number prefix/suffix.

11

' To mark quote around special characters.

Example

在此示例中,我们会按照不同的模式对数字进行格式化。

In this example, we’re formatting numbers based on different patterns.

import java.text.DecimalFormat;

public class I18NTester {
   public static void main(String[] args) {
      String pattern = "###.###";
      double number = 123456789.123;

      DecimalFormat numberFormat = new DecimalFormat(pattern);

      System.out.println(number);

      //pattern ###.###
      System.out.println(numberFormat.format(number));

      //pattern ###.#
      numberFormat.applyPattern("###.#");
      System.out.println(numberFormat.format(number));

      //pattern ###,###.##
      numberFormat.applyPattern("###,###.##");
      System.out.println(numberFormat.format(number));

      number = 9.34;

      //pattern 000.###
      numberFormat.applyPattern("000.##");
      System.out.println(numberFormat.format(number));
   }
}

Output

它将打印以下结果。

It will print the following result.

1.23456789123E8
1,2345,6789.12

Java Internationalization - Locale Specific DecimalFormat

默认情况下,DecimalFormat 对象使用 JVM 的区域设置。我们可以在创建 DecimalFormat 对象时使用 NumberFormat 类更改默认区域设置。在以下示例中,我们将针对两个不同区域设置使用相同的模式,您可以在输出中发现差异。

By default, DecimalFormat object is using the JVM’s locale. We can change the default locale while creating the DecimalFormat object using NumberFormat class. In the example below, we’ll use same pattern for two different locale and you can spot the difference in the output.

Example

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

public class I18NTester {
   public static void main(String[] args) {
      String pattern = "###.##";
      double number = 123.45;

      Locale enlocale  = new Locale("en", "US");
      Locale dalocale  = new Locale("da", "DK");

      DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(enlocale);
      decimalFormat.applyPattern(pattern);

      System.out.println(decimalFormat.format(number));

      decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(dalocale);
      decimalFormat.applyPattern(pattern);

      System.out.println(decimalFormat.format(number));
   }
}

Output

它将打印以下结果。

It will print the following result.

123.45
123,45

Java Internationalization - DecimalFormatSymbols Class

使用 DecimalFormatSymbols 类,可以更改默认分隔符符号、分组分隔符符号等。以下示例对此进行了说明。

Using DecimalFormatSymbols class, the default separator symbols, grouping separator symbols etc. can be changed. Following example is illustrating the same.

Example

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;

public class I18NTester {
   public static void main(String[] args) {
      String pattern = "#,###.###";
      double number = 126473.4567;

      DecimalFormat decimalFormat = new DecimalFormat(pattern);

      System.out.println(decimalFormat.format(number));

      DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
      decimalFormatSymbols.setDecimalSeparator(';');
      decimalFormatSymbols.setGroupingSeparator(':');

      decimalFormat = new DecimalFormat(pattern, decimalFormatSymbols);

      System.out.println(decimalFormat.format(number));
   }
}

Output

它将打印以下结果。

It will print the following result.

126,473.457
126:473;457

Java Internationalization - Grouping Digits

使用 DecimalFormat 的 setGroupingSize() 方法,可以更改数字的默认分组。以下示例对此进行了说明。

Using setGroupingSize() method of DecimalFormat, default grouping of numbers can be changed. Following example is illustrating the same.

Example

import java.text.DecimalFormat;

public class I18NTester {
   public static void main(String[] args) {
      double number = 121223232473.4567;

      DecimalFormat decimalFormat = new DecimalFormat();

      System.out.println(number);
      System.out.println(decimalFormat.format(number));

      decimalFormat.setGroupingSize(4);
      System.out.println(decimalFormat.format(number));

   }
}

Output

它将打印以下结果。

It will print the following result.

1.212232324734567E11
121,223,232,473.457
1212,2323,2473.457

Java Internationalization - DateFormat Class

java.text.DateFormat 类根据语言环境格式化日期。由于不同的国家使用不同的格式显示日期。该类在处理应用程序的国际化中的日期时非常有用。以下示例展示了如何创建和使用 DateFormat 类。

java.text.DateFormat class formats dates as per the locale. As different coutries use different formats to display dates. This class is extremely useful in dealing with dates in Internationalization of application. Following example show how to create and use DateFormat Class.

Example

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

public class I18NTester {
   public static void main(String[] args) {
      Locale locale = new Locale("da","DK");

      DateFormat dateFormat = DateFormat.getDateInstance();

      System.out.println(dateFormat.format(new Date()));

      dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);

      System.out.println(dateFormat.format(new Date()));
   }
}

Output

它将打印以下结果。

It will print the following result.

Nov 29, 2017
29-11-2017

Java Internationalization - Formatting Dates

DateFormat 类提供各种格式来格式化日期。以下是其中一些格式的列表。

DateFormat class provides various formats to format the date. Following is list of some of the formats.

  1. DateFormat.DEFAULT

  2. DateFormat.SHORT

  3. DateFormat.MEDIUM

  4. DateFormat.LONG

  5. DateFormat.FULL

Example

在以下示例中,我们将演示如何使用不同的格式。

In following example we’ll show how to use different formats.

import java.text.DateFormat;
import java.util.Date;

public class I18NTester {
   public static void main(String[] args) {

      DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT);

      System.out.println(dateFormat.format(new Date()));

      dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);

      System.out.println(dateFormat.format(new Date()));

      dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);

      System.out.println(dateFormat.format(new Date()));

      dateFormat = DateFormat.getDateInstance(DateFormat.LONG);

      System.out.println(dateFormat.format(new Date()));

      dateFormat = DateFormat.getDateInstance(DateFormat.FULL);

      System.out.println(dateFormat.format(new Date()));

   }
}

Output

它将打印以下结果。

It will print the following result.

Nov 29, 2017
11/29/17
Nov 29, 2017
November 29, 2017
Wednesday, November 29, 2017

Java Internationalization - Formatting Time

DateFormat 类提供了各种格式来格式化时间。应使用 DateFormat.getTimeInstance() 方法。请参见以下示例。

DateFormat class provides various formats to format the time. DateFormat.getTimeInstance() method is to be used. See the example below.

Example

在以下示例中,我们将展示如何使用不同的格式来格式化时间。

In following example we’ll show how to use different formats to format time.

import java.text.DateFormat;
import java.util.Date;

public class I18NTester {
   public static void main(String[] args) {

      DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.DEFAULT);

      System.out.println(dateFormat.format(new Date()));

      dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT);

      System.out.println(dateFormat.format(new Date()));

      dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM);

      System.out.println(dateFormat.format(new Date()));

      dateFormat = DateFormat.getTimeInstance(DateFormat.LONG);

      System.out.println(dateFormat.format(new Date()));

      dateFormat = DateFormat.getTimeInstance(DateFormat.FULL);

      System.out.println(dateFormat.format(new Date()));

   }
}

Output

它将打印以下结果。

It will print the following result.

4:11:21 PM
4:11 PM
4:11:21 PM
4:11:21 PM IST
4:11:21 PM IST

Java Internationalization - Formatting Date and Time

DateFormat 类通过提供各种格式,将日期和时间组合起来进行格式化。须使用 DateFormat.getDateTimeInstance() 方法。请参见下面的示例。

DateFormat class provides various formats to format the date and time together. DateFormat.getDateTimeInstance() method is to be used. See the example below.

Example

在以下示例中,我们将演示如何使用不同的格式对日期和时间进行格式化。

In following example we’ll show how to use different formats to format date and time.

import java.text.DateFormat;
import java.util.Date;

public class I18NTester {
   public static void main(String[] args) {

      DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT);

      System.out.println(dateFormat.format(new Date()));

      dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);

      System.out.println(dateFormat.format(new Date()));

      dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);

      System.out.println(dateFormat.format(new Date()));

      dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);

      System.out.println(dateFormat.format(new Date()));

      dateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);

      System.out.println(dateFormat.format(new Date()));

   }
}

Output

它将打印以下结果。

It will print the following result.

Nov 29, 2017 4:16:13 PM
11/29/17 4:16 PM
Nov 29, 2017 4:16:13 PM
November 29, 2017 4:16:13 PM IST
Wednesday, November 29, 2017 4:16:13 PM IST

Java Internationalization - SimpleDateFormat Class

java.text.SimpleDateFormat 类根据给定的模式对日期进行格式化。它还用于从字符串中解析日期,字符串中包含指定格式的日期。请参见以下使用 SimpleDateFormat 类的示例。

java.text.SimpleDateFormat class formats dates as per the given pattern. It is also used to parse dates from string where string contains date in mentioned format. See the following example of using SimpleDateFormat class.

Example

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class I18NTester {
   public static void main(String[] args) throws ParseException {

      String pattern = "dd-MM-yyyy";

      SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

      Date date = new Date();

      System.out.println(date);
      System.out.println(simpleDateFormat.format(date));

      String dateText = "29-11-2017";

      date = simpleDateFormat.parse(dateText);

      System.out.println(simpleDateFormat.format(date));
   }
}

Output

它将打印以下结果。

It will print the following result.

Wed Nov 29 17:01:22 IST 2017
29-11-2017
29-11-2017

Java Internationalization - Locale specific SimpleDateFormat

区域设置可用于在 SimpleDateFormat 类的模式中创建特定于区域设置的格式化。请参阅以下使用特定于区域设置的 SimpleDateFormat 类的示例。

Locale can be used to create locale specific formatting over a pattern in SimpleDateFormat class. See the following example of using locale specific SimpleDateFormat class.

Example

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class I18NTester {
   public static void main(String[] args) throws ParseException {

      Locale locale = new Locale("da", "DK");
      String pattern = "EEEEE MMMMM yyyy";

      SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

      Date date = new Date();

      System.out.println(date);
      System.out.println(simpleDateFormat.format(date));

      simpleDateFormat = new SimpleDateFormat(pattern,locale);

      System.out.println(simpleDateFormat.format(date));
   }
}

Output

它将打印以下结果。

It will print the following result.

Wed Nov 29 17:48:14 IST 2017
Wednesday November 2017
onsdag november 2017

Java Internationalization - DecimalFormatSymbols Class

使用 DecimalFormatSymbols 类,可以更改默认分隔符符号、分组分隔符符号等。以下示例对此进行了说明。

Using DecimalFormatSymbols class, the default separator symbols, grouping separator symbols etc. can be changed. Following example is illustrating the same.

Example

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;

public class I18NTester {
   public static void main(String[] args) {
      String pattern = "#,###.###";
      double number = 126473.4567;

      DecimalFormat decimalFormat = new DecimalFormat(pattern);

      System.out.println(decimalFormat.format(number));

      DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
      decimalFormatSymbols.setDecimalSeparator(';');
      decimalFormatSymbols.setGroupingSeparator(':');

      decimalFormat = new DecimalFormat(pattern, decimalFormatSymbols);

      System.out.println(decimalFormat.format(number));
   }
}

Output

它将打印以下结果。

It will print the following result.

126,473.457
126:473;457

Java Internationalization - Date Format Patterns

以下是字符在日期格式化模式中的用途。

Followings is the use of characters in date formatting patterns.

Sr.No.

Class & Description

1

G To display Era.

2

y To display Year. Valid values yy, yyyy.

3

M To display Month. Valid values MM, MMM or MMMMM.

4

d To display day of month. Valid values d, dd.

5

h To display hour of day (1-12 AM/PM). Valid value hh.

6

H To display hour of day (0-23). Valid value HH.

7

m To display minute of hour (0-59). Valid value mm.

8

s To display second of minute (0-59). Valid value ss.

9

S To display milliseconds of minute (0-999). Valid value SSS.

10

E To display Day in week (e.g Monday, Tuesday etc.)

11

D To display Day in year (1-366).

12

F To display Day of week in month (e.g. 1st Thursday of December).

13

w To display Week in year (1-53).

14

W To display Week in month (0-5)

15

a To display AM / PM

16

k To display Hour in day (1-24).

17

K To display Hour in day, AM / PM (0-11).

18

z To display Time Zone.

Example

在这个示例中,我们根据不同的模式设置日期的格式。

In this example, we’re formatting dates based on different patterns.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class I18NTester {
   public static void main(String[] args) throws ParseException {

      String pattern = "dd-MM-yy";
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
      Date date = new Date();
      System.out.println(simpleDateFormat.format(date));

      pattern = "MM-dd-yyyy";
      simpleDateFormat = new SimpleDateFormat(pattern);
      System.out.println(simpleDateFormat.format(date));

      pattern = "yyyy-MM-dd HH:mm:ss";
      simpleDateFormat = new SimpleDateFormat(pattern);
      System.out.println(simpleDateFormat.format(date));

      pattern = "EEEEE MMMMM yyyy HH:mm:ss.SSSZ";
      simpleDateFormat = new SimpleDateFormat(pattern);
      System.out.println(simpleDateFormat.format(date));
}
}

Output

它将打印以下结果。

It will print the following result.

29-11-17
11-29-2017
2017-11-29 18:47:42
Wednesday November 2017 18:47:42.787+0530

Java Internationalization - UTC

UTC 代表协调世界时。它是时间标准,在世界各地普遍使用。所有时区都与 UTC 进行比较计算,作为偏移量。例如,丹麦哥本哈根的时间是 UTC + 1,表示 UTC 时间加一小时。它与夏令时无关,应该用于在数据库中存储日期和时间。

UTC stands for Co-ordinated Universal Time. It is time standard and is commonly used across the world. All time zones are computed comparatively with UTC as offset. For example, time in Copenhagen, Denmark is UTC + 1 means UTC time plus one hour. It is independent of Day light savings and should be used to store date and time in databases.

Conversion of time zones

下面的示例将展示各种时区的转换。我们将打印一天中的小时和时间(以毫秒为单位)。第一个将变化,第二个将保持不变。

Following example will showcase conversion of various time zones. We’ll print hour of the day and time in milliseconds. First will vary and second will remain same.

Example

import java.text.ParseException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class I18NTester {
   public static void main(String[] args) throws ParseException {

      Calendar date = new GregorianCalendar();

      date.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
      date.set(Calendar.HOUR_OF_DAY, 12);

      System.out.println("UTC: " + date.get(Calendar.HOUR_OF_DAY));
      System.out.println("UTC: " + date.getTimeInMillis());

      date.setTimeZone(TimeZone.getTimeZone("Europe/Copenhagen"));
      System.out.println("CPH: " + date.get(Calendar.HOUR_OF_DAY));
      System.out.println("CPH: " + date.getTimeInMillis());

      date.setTimeZone(TimeZone.getTimeZone("America/New_York"));
      System.out.println("NYC: " + date.get(Calendar.HOUR_OF_DAY));
      System.out.println("NYC: " + date.getTimeInMillis());
   }
}

它将打印以下结果。

It will print the following result.

UTC: 12
UTC: 1511956997540
CPH: 13
CPH: 1511956997540
NYC: 7
NYC: 1511956997540

Available Time Zones

下面的示例将展示系统中可用的时区。

Following example will showcase the time zones available with the system.

Example

import java.text.ParseException;
import java.util.TimeZone;

public class I18NTester {
   public static void main(String[] args) throws ParseException {
      String[] availableIDs = TimeZone.getAvailableIDs();

      for(String id : availableIDs) {
         System.out.println("Timezone = " + id);
      }
   }
}

它将打印以下结果。

It will print the following result.

Timezone = Africa/Abidjan
Timezone = Africa/Accra
...
Timezone = VST

Java Internationalization - Unicode Conversion from/to String

在 Java 中,文本以 Unicode 格式内部存储。如果输入/输出采用不同格式,则需要进行转换。

In java, text is internally stored in Unicode format. If input/output is in different format then conversion is required.

Conversion

以下示例将展示如何将 Unicode 字符串转换为 UTF8 字节数组,将 UTF8 字节数组转换为 Unicode 字节数组。

Following example will showcase conversion of a Unicode String to UTF8 byte[] and UTF8 byte[] to Unicode byte[].

Example

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.ParseException;

public class I18NTester {
   public static void main(String[] args) throws ParseException, UnsupportedEncodingException {

      String unicodeString = "\u00C6\u00D8\u00C5" ;

      //convert Unicode to UTF8 format
      byte[] utf8Bytes = unicodeString.getBytes(Charset.forName("UTF-8"));
      printBytes(utf8Bytes, "UTF 8 Bytes");

      //convert UTF8 format to Unicode
      String converted = new String(utf8Bytes, "UTF8");
      byte[] unicodeBytes = converted.getBytes();
      printBytes(unicodeBytes, "Unicode Bytes");
   }

   public static void printBytes(byte[] array, String name) {
      for (int k = 0; k < array.length; k++) {
         System.out.println(name + "[" + k + "] = " + array[k]);

      }
   }
}

它将打印以下结果。

It will print the following result.

UTF 8 Bytes[0] = -61
UTF 8 Bytes[1] = -122
UTF 8 Bytes[2] = -61
UTF 8 Bytes[3] = -104
UTF 8 Bytes[4] = -61
UTF 8 Bytes[5] = -123
Unicode Bytes[0] = -58
Unicode Bytes[1] = -40
Unicode Bytes[2] = -59

Java Internationalization - Unicode Conversion from/to Reader/Writer

读取器和写入器类是面向字符的流类。这些可用于读取和转换 Unicode 字符。

Reader and Writer classes are character oriented stream classes. These can be used to read and convert Unicode characters.

Conversion

以下示例将展示如何使用读取器和写入器类将 Unicode 字符串转换为 UTF8 字节数组,将 UTF8 字节数组转换为 Unicode 字节数组。

Following example will showcase conversion of a Unicode String to UTF8 byte[] and UTF8 byte[] to Unicode byte[] using Reader and Writer classes.

Example

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.text.ParseException;

public class I18NTester {
   public static void main(String[] args) throws ParseException, IOException {

      String input = "This is a sample text" ;

      InputStream inputStream = new ByteArrayInputStream(input.getBytes());

      //get the UTF-8 data
      Reader reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));

      //convert UTF-8 to Unicode
      int data = reader.read();
      while(data != -1){
         char theChar = (char) data;
         System.out.print(theChar);
         data = reader.read();
      }
      reader.close();

      System.out.println();

      //Convert Unicode to UTF-8 Bytes
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      Writer writer = new OutputStreamWriter(outputStream, Charset.forName("UTF-8"));

      writer.write(input);
      writer.close();

      String out = new String(outputStream.toByteArray());

      System.out.println(out);
   }
}

它将打印以下结果。

It will print the following result.

This is a sample text
This is a sample text