自定义格式
原文: 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
包含要显示的格式化日期和时间。
Date today;
String output;
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(pattern, currentLocale);
today = new Date();
output = formatter.format(today);
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
对象的语句中进行了硬编码:
Date today;
String result;
SimpleDateFormat formatter;
formatter = new SimpleDateFormat("EEE d MMM yy", currentLocale);
today = new Date();
result = formatter.format(today);
System.out.println("Locale: " + currentLocale.toString());
System.out.println("Result: " + result);
当currentLocale
设置为不同的值时,前面的代码示例生成此输出:
Locale: fr_FR
Result: mar. 30 juin 09
Locale: de_DE
Result: Di 30 Jun 09
Locale: en_US
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 | 文字形式 |