Java的DateTimeFormatter/SimpleDateFormat如何转义特殊字符

对于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]

 

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值