Java 在 SimpleDateFormat 模式字符串中使用字母字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2416809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:19:43  来源:igfitidea点击:

Using Alphabetic Characters in SimpleDateFormat Pattern String

javadatetimeformattingsimpledateformat

提问by Gordon

Is it possible to include an alphabetic character in a SimpleDateFormat Pattern String?

是否可以在 SimpleDateFormat 模式字符串中包含字母字符?

I am trying to create a format string where the letter 'T' is included before the time for example:

我正在尝试创建一个格式字符串,其中在时间之前包含字母“T”,例如:

2003-11-15T09:30:47-05:00.

2003-11-15 T09:30:47-05:00。

I am currently using yyyy-MM-ddhh:mm:ssZas the pattern string.

我目前yyyy-MM-ddhh:mm:ssZ用作模式字符串。

If I change it to yyyy-MM-ddThh:mm:ssZit will throw an exception as 'A' to 'Z' and 'a' to 'z' are reserved.

如果我将其更改为yyyy-MM-ddThh:mm:ssZ它会抛出异常,因为 'A' 到 'Z' 和 'a' 到 'z' 是保留的。

Is there any solution that does not involve using two DateFormats?

有没有不涉及使用两个 DateFormats 的解决方案?

采纳答案by Joey

Surrounding the Twith single quotes should work:

周围的T单引号应该工作:

yyyy-MM-dd'T'hh:mm:ssZ

Quoting from the documentation(emphasis mine):

引用文档(强调我的):

Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from 'A'to 'Z'and from 'a'to 'z'are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation."''"represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.

日期和时间格式由日期和时间模式字符串指定。在日期和时间模式字符串中,未加引号的字母 from 'A'to'Z'和 from 'a'to'z'被解释为表示日期或时间字符串组成部分的模式字母。可以使用单引号 ( ')引用文本以避免解释。"''"代表单引号。不解释所有其他字符;它们只是在格式化期间复制到输出字符串中,或​​者在解析期间与输入字符串匹配。

Your specific use case is even included as an example:

您的特定用例甚至包括作为示例:

Date and Time Pattern            Result
-------------------------------------------------------------
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"     2001-07-04T12:08:56.235-0700