使用getTimeInstance()
Java中的方法来获取您设置的语言环境的时间格式。DateFormat.MEDIUM是中等样式模式的常量。
首先,我们将创建一个Date对象-
Date dt = new Date(); DateFormat dateFormat;
让我们使用DateFormat.MEDIUM为其他语言环境设置时间格式
dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CANADA); System.out.println("Locale CANADA = " + dateFormat.format(dt)); dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ITALY); System.out.println("Locale ITALY = " + 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; //用MEDIUM常数显示时间 dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.FRENCH); System.out.println("Locale FRENCH = " + dateFormat.format(dt)); dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.GERMANY); System.out.println("Locale GERMANY = " + dateFormat.format(dt)); dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CHINESE); System.out.println("Locale CHINESE = " + dateFormat.format(dt)); dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CANADA); System.out.println("Locale CANADA = " + dateFormat.format(dt)); dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ITALY); System.out.println("Locale ITALY = " + dateFormat.format(dt)); dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.TAIWAN); System.out.println("Locale TAIWAN = " + dateFormat.format(dt)); } }
输出结果
Locale FRENCH = 09:47:50 Locale GERMANY = 09:47:50 Locale CHINESE = 9:47:50 Locale CANADA = 9:47:50 AM Locale ITALY = 9.47.50 Locale TAIWAN = 上午 09:47:50