使用 预定义格式
Version note:
DateFormat类允许您以对语言环境敏感的方式使用 预定义的样式来格式化日期和时间。以下各节说明如何将DateFormat
类与名为DateFormatDemo.java的程序一起使用。
Dates
使用DateFormat
类格式化日期是一个两步过程。首先,使用getDateInstance
方法创建一个格式化程序。其次,调用format
方法,该方法返回一个包含格式化日期的String
。下面的示例通过调用这两个方法来格式化今天的日期:
Date today;
String dateOut;
DateFormat dateFormatter;
dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, currentLocale);
today = new Date();
dateOut = dateFormatter.format(today);
System.out.println(dateOut + " " + currentLocale.toString());
此代码生成的输出如下。请注意,日期的格式随着Locale
的不同而不同。由于DateFormat
是区域设置敏感的,因此它会照顾每个Locale
的格式详细信息。
30 juin 2009 fr_FR
30.06.2009 de_DE
Jun 30, 2009 en_US
前面的代码示例指定了DEFAULT
格式样式。 DEFAULT
样式只是DateFormat
类提供的 预定义格式样式之一,如下所示:
-
DEFAULT
-
SHORT
-
MEDIUM
-
LONG
-
FULL
下表显示了如何在美国和法国语言环境中设置每种样式的日期格式:
samples 日期格式
Style | U.S. Locale | French Locale |
---|---|---|
DEFAULT | 2009 年 6 月 30 日 | 30 2009 年 6 月 |
SHORT | 6/30/09 | 30/06/09 |
MEDIUM | 2009 年 6 月 30 日 | 30 2009 年 6 月 |
LONG | 2009 年 6 月 30 日 | 30 2009 年 6 月 |
FULL | 2009 年 6 月 30 日,星期二 | 2009 年 3 月 30 日狂欢 |
Times
Date
对象代表日期和时间。 DateFormat
类的格式化时间与格式化日期类似,不同之处在于,您使用getTimeInstance
方法创建格式化程序,如下所示:
DateFormat timeFormatter =
DateFormat.getTimeInstance(DateFormat.DEFAULT, currentLocale);
下表显示了美国和德国语言环境的各种 预定义格式样式:
采样时间格式
Style | U.S. Locale | German Locale |
---|---|---|
DEFAULT | 7:03:47 AM | 7:03:47 |
SHORT | 7:03 AM | 07:03 |
MEDIUM | 7:03:47 AM | 07:03:07 |
LONG | 太平洋标准时间 7:03:47 AM | 07:03:45 PDT |
FULL | 太平洋标准时间 7:03:47 AM | 7 .03 UPDT |
日期和时间
要在同一String
中显示日期和时间,请使用getDateTimeInstance
方法创建格式化程序。第一个参数是日期样式,第二个参数是时间样式。第三个参数是Locale
。这是一个简单的例子:
DateFormat formatter = DateFormat.getDateTimeInstance(
DateFormat.LONG,
DateFormat.LONG,
currentLocale);
下表显示了美国和法国语言环境的日期和时间格式样式:
samples 日期和时间格式
Style | U.S. Locale | French Locale |
---|---|---|
DEFAULT | 2009 年 6 月 30 日 7:03:47 AM | 30 2009 年 6 月 7 日 03:03:47 |
SHORT | 6/30/09 7:03 AM | 30/06/09 07:03 |
MEDIUM | 2009 年 6 月 30 日 7:03:47 AM | 30 2009 年 6 月 7 日 03:03:47 |
LONG | 2009 年 6 月 30 日,太平洋夏令时间 7:03:47 | 30 juin 2009 07:03:47 PDT |
FULL | 2009 年 6 月 30 日,星期二,太平洋时间上午 7:03:47 | 2009 年 6 月 30 日 3 月 30 日 PDT |