是否可以在 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/