使用getTimeInstance()
Java中的方法获取您设置的语言环境的时间格式。DateFormat.SHORT是短样式模式的常量。
首先,我们将创建Date对象
Date dt = new Date(); DateFormat dateFormat;
让我们使用DateFormat.SHORT格式化不同语言环境的时间
dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.CHINESE); System.out.println("Locale CHINESE = " + dateFormat.format(dt)); dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.CANADA); System.out.println("Locale CANADA = " + dateFormat.format(dt));
以下是一个例子-
import java.text.DateFormat; import java.util.Date; import java.util.Locale; public class Demo { public static void main(String args[]) { Date dt = new Date(); DateFormat dateFormat; //用SHORT常量显示时间 dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.FRENCH); System.out.println("Locale FRENCH = " + dateFormat.format(dt)); dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.GERMANY); System.out.println("Locale GERMANY = " + dateFormat.format(dt)); dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.CHINESE); System.out.println("Locale CHINESE = " + dateFormat.format(dt)); dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.CANADA); System.out.println("Locale CANADA = " + dateFormat.format(dt)); dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.ITALY); System.out.println("Locale ITALY = " + dateFormat.format(dt)); dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.TAIWAN); System.out.println("Locale TAIWAN = " + dateFormat.format(dt)); } }
输出结果
Locale FRENCH = 09:45 Locale GERMANY = 09:45 Locale CHINESE = 上午9:45 Locale CANADA = 9:45 AM Locale ITALY = 9.45 Locale TAIWAN = 上午 9:45