java - 在 SimpleDateFormat 模式字符串中使用字母字符

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

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

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

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

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

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

最佳答案

用单引号将 T 括起来应该可以:

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

引自 the documentation (强调我的):

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.

您的具体用例甚至被包括在内作为示例:

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

https://stackoverflow.com/questions/2416809/

相关文章:

c++ - 我应该在我的 C++ 代码中使用 printf 吗?

c# - 文件大小格式提供程序

java - 将 BigDecimal 格式化为最多 2 个十进制数字的字符串,在小数部分删除 0

objective-c - 将字符串转换为 NSDate

c - 如何在 C 中使用逗号作为千位分隔符来格式化数字?

excel - 如何在 Excel 中将单元格的字节格式设置为 KB、MB、GB 等?

xml - 在 Eclipse 中格式化 XML 代码

intellij-idea - 如何在 WebStorm 中自动格式化代码?

objective-c - 将秒整数转换为 HH :MM, iPhone

python - 在 Python 中的文件末尾声明函数