对于JAVA中的 DateTimeFormatter,或者主要是为了日期能够格式化地生成字符串,比如可以使用 yyyy-MM-dd HH:mm:ss 来生成 2019-10-16 21:00:16 这种格式的字符串。
这里有一个需求,希望生成 [2019-10-16 21:00:16] 这种字符串。可以看到它的左右两边多了中括号,而此时,我如果使用
public static void main(String[] args) {
String s = LocalDateTime.now().format(DateTimeFormatter.ofPattern("[yyyy-MM-dd HH:mm:ss]"));
System.out.println(s);
}
发现打印出来的是:
2019-10-16 21:00:16
中括号消失了!
我查阅了资料:https://stackoverflow.com/questions/2138085/java-date-format-including-additional-characters 和 https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html 得知,
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.
意思就是说:
在SimpleDateFormat or DateTimeFormatter 的模式字符串中,从 A~Z 以及 a~z 的字母(未加引号的)会被解释为时间组成部分的模式字母。对于文本型的字符,可以使用单引号 (
'
) 进行引用以避免被编译器解析。 使用"''"
来表示单引号。 对于其他其他的字符,编译器均不解释。它们会在输出时被简单地复制进输出字符串中,或者在解析过程中与输入字符串进行匹配。
那么,对于我的中括号,如果希望能显示出来,则需要用单引号来包起来:
public static void main(String[] args) {
String s = LocalDateTime.now().format(DateTimeFormatter.ofPattern("'['yyyy-MM-dd HH:mm:ss']'")) + " REWRITE ";
System.out.println(s);
}
上述代码的输出就是
[2019-10-16 21:00:16]