自定义格式

原文: https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html


Version note: This Date and Time section uses the date and time APIs in the java.util package. The java.time APIs, available in the JDK 8 release, provides a comprehensive date and time model that offers significant improvements over the java.util classes. The java.time APIs are described in the Date Time trail. The Legacy Date-Time Code page might be of particular interest.


上一节使用预定义格式描述了DateFormat类提供的格式样式。在大多数情况下,这些预定义格式就足够但是,如果要创建自己的自定义格式,可以使用 SimpleDateFormat 类。

下面的代码示例演示了SimpleDateFormat类的方法。您可以在名为 SimpleDateFormatDemo 的文件中找到示例的完整源代码。

关于模式

创建SimpleDateFormat对象时,指定模式String。模式String的内容决定了日期和时间的格式。有关模式语法的完整说明,请参见日期格式模式语法中的表。

以下代码根据传递给SimpleDateFormat构造器的模式String格式化日期和时间。 format方法返回的String包含要显示的格式化日期和时间。

  1. Date today;
  2. String output;
  3. SimpleDateFormat formatter;
  4. formatter = new SimpleDateFormat(pattern, currentLocale);
  5. today = new Date();
  6. output = formatter.format(today);
  7. System.out.println(pattern + " " + output);

下表显示了指定 U.S. Locale时上一代码示例生成的输出:

Customized Date and Time Formats | 图案 | 产量 | | —- | —- | | DD.MM.YY | 30.06.09 | | yyyy.MM.dd G’at’hh:mm:ss z | 公元 2009.06.30 PDT 08:29:36 | | EEE,MMM d,’’yy | 09 年 6 月 30 日星期二 | | h:mm a | 晚上 8:29 | | H:毫米 | 8:29 | | H:MM:SS:SSS | 8:28:36:249 | | K:mm a,z | 上午 8:29,PDT | | yyyy.MMMMM.dd GGG hh:mm aaa | 2009.June.30 AD 08:29 AM |

模式和区域设置

SimpleDateFormat类是区域设置敏感的。如果在没有Locale参数的情况下实例化SimpleDateFormat,它将根据默认Locale格式化日期和时间。模式和Locale都决定了格式。对于相同的模式,SimpleDateFormat可能会在Locale变化时以不同方式格式化日期和时间。

在下面的示例代码中,模式在创建SimpleDateFormat对象的语句中进行了硬编码:

  1. Date today;
  2. String result;
  3. SimpleDateFormat formatter;
  4. formatter = new SimpleDateFormat("EEE d MMM yy", currentLocale);
  5. today = new Date();
  6. result = formatter.format(today);
  7. System.out.println("Locale: " + currentLocale.toString());
  8. System.out.println("Result: " + result);

currentLocale设置为不同的值时,前面的代码示例生成此输出:

  1. Locale: fr_FR
  2. Result: mar. 30 juin 09
  3. Locale: de_DE
  4. Result: Di 30 Jun 09
  5. Locale: en_US
  6. Result: Tue 30 Jun 09

日期格式模式语法

您可以从下表中的符号列表中为日期和时间设计自己的格式模式:

符号 含义 介绍
G 时代指示符 文本 广告
ÿ 2009 年
中号 一年一个月 文字&数 七月& 07
d 一个月一天 10
H 上午/下午(1-12) 12
H 小时(0-23) 0
分钟 三十
小号 第二分钟 55
小号 毫秒 978
Ë 一周中的一天 文本 星期二
d 一年中的一天 189
F 一个月中的某一天 2(7 月的第 2 个星期三)
w ^ 一年一周 27
w ^ 一周一个月 2
一个 上午/下午标记 文本 下午
ķ 小时(1-24) 24
ķ 上午/下午(0-11) 0
ž 时区 文本 太平洋标准时间
逃避文字 分隔符 (没有)
单引号 文字

不是字母的字符被视为带引号的文本。也就是说,即使它们没有包含在单引号内,它们也会出现在格式化文本中。

您指定的符号字母数也决定了格式。例如,如果“zz”模式导致“PDT”,则“zzzz”模式生成“太平洋夏令时”。下表总结了这些规则:

介绍 符号数 结果
文本 1 - 3 缩写形式,如果存在的话
文本 > = 4 完整形式
最低位数是必需的 较短的数字用零填充(一年,如果’y’的计数为 2,则年份被截断为 2 位数)
文字&数 1 - 2 数字表格
文字&数 3 文字形式