在Java中有没有类似于php date()样式的格式?我的意思是,在php中我可以反斜杠转义字符,让它们按字面意思处理。也就是说,yyyy \y\e\a\r将变成2010年。我在Java中没有找到类似的东西,所有的例子都只处理内置的日期格式。
具体来说,我将处理JCalendar日期选取器及其dateFormatString属性。
我需要它,因为在我的语言环境中,需要用日期格式写各种各样的附加内容,比如d.(表示天)在天之后,m.(表示年)在年之后,等等。
在最坏的情况下,我可以使用字符串替换或regexp,但也许有一个更简单的方法?
5条答案
按热度按时间l7mqbcuq1#
当然,在SimpleDateFormat中可以包含文字字符串:
在日期和时间模式字符串中,从'A'到'Z'以及从'a'到'z'的无引号字母被解释为表示日期或时间字符串组成部分的模式字母。可以使用单引号(')将文本引起来以避免解释。“''”表示单引号。不解释所有其他字符;它们只是在格式化过程中复制到输出字符串中,或者在解析过程中与输入字符串匹配。
koaltpgm2#
为了完整起见,Java 8的
DateTimeFormatter
也支持这一点:bq8i3lrv3#
Java.时间
已经是Mark Jeronimus said it了。我正在充实它。只要把要打印的文本放在单引号里就行了。
刚才运行时输出:
如果您使用的是
DateTimeFormatterBuilder
及其appendPattern
方法,请以相同的方式使用单引号。或者使用其appendLiteral
方法,但不使用单引号。那么,我们如何在格式中加上单引号呢?两个单引号会产生一个单引号。双单引号是否在单引号内并不重要:
10英尺28英寸34英寸
02:00 AM,太平洋夏令时
以上所有的格式化程序都可以用于解析。例如:
十六点四十三分五十六秒
大约10年前提出这个问题时使用的
SimpleDateFormat
类是出了名的麻烦,而且早就过时了。我建议您改用java.time,这是现代Java日期和时间API。这就是我演示它的原因。链接
DateTimeFormatter
toiithl64#
您可以按照java.util.Formatter中的说明使用String.format:
t8e9dugd5#
java.text.SimpleDateFormat
您将在此处获得更多信息link text