Formatter VS DateFormat 不一致

Formatter VS DateFormat inconsistencies

前提

这个问题可能被合理地认为过于宽泛或观点驱动,但我觉得无论如何我都必须冒险。

问题

在 Java 的 Formatter VS SimpleDateFormat API 中说明的 date/time 转换格式之间存在许多难以理解的不一致之处。

例如:

问题(s)

简单日期格式

正如@Tunaki 所说,SimpleDateFormat 使用由 Date Field Symbol Table (which is standardized by CLDRUnicode 公共语言环境数据存储库 定义的模式字符。

该项目被许多公司广泛使用,例如Google、IBM、Microsoft、Apple 等,以实现广泛的语言环境数据标准存储库,以及软件国际化和本地化。这就是为什么某些 date/time 模式与来自不同编程语言的其他模式非常相似的原因。

此外,除了 way we use date, time and time zone 之外,指定排序规则、键盘映射、数字、货币等标准非常重要。此外,它定义了当我们尝试解析日期时会发生什么日语,例如

为了理解这一点,我们必须说明 what means a "parsing" process:

  • A mapping between a point in time (UDate) and a set of calendar fields, which in turn depends on:
    • The rules of a particular calendar system (e.g. Gregorian, Buddhist, Chinese Lunar)
    • The time zone
  • A mapping between a set of calendar fields and a formatted textual representation, which depends on the fields selected for display, their display style, and the conventions of a particular locale.

因此,有必要知道 "MMMMdjmm" 的框架可能会针对不同的区域设置产生以下格式模式:

Locale | format pattern
------ | ---------------------
en_US  | "MMMM d 'at' h:mm a"
es_ES  | "d 'de' MMMM, H:mm"  
ja_JP  | "M月d日 H:mm"

格式化程序

之所以Formatter "adopted"不同的格式化模式是因为这个class应该是printf风格格式字符串的解释器,它非常接近GNU date and POSIX strftime(3c) realities (as the official docs states).

来自 GNU 文档:

The output of the date command is not always acceptable as a date string, not only because of the language problem, but also because there is no standard meaning for time zone items like 'IST'.

When using date to generate a date string intended to be parsed later, specify a date format that is independent of language and that does not use time zone items other than 'UTC' and 'Z'.

让我们看一个简单的 date/time GNU 示例:

TZ=UTC0 date +'%Y-%m-%d %H:%M:%SZ'
// Output: 2004-03-01 00:21:42Z

注意printf风格以及Formatter class.

相同转换字符的使用

但是,文档还说它们只是相似,而不是相同。这是因为 Java 为特定字段选择了一些灵活性,例如 'z' 案例:

RFC 822 style numeric time zone offset from GMT, e.g. -0800. This value will be adjusted as necessary for Daylight Saving Time.