java.time
马克·杰罗尼姆斯已经说过了。我正在充实它。只需将要打印的文本按字面意思放在单引号内。
DateTimeFormatter yearFormatter = DateTimeFormatter.ofPattern("yyyy 'year'");
System.out.println(LocalDate.of(2010, Month.FEBRUARY, 3).format(yearFormatter));
System.out.println(Year.of(2010).format(yearFormatter));
System.out.println(ZonedDateTime.now(ZoneId.of("Europe/Vilnius")).format(yearFormatter));
刚才运行时的输出:
2010 year
2010 year
2019 year
如果您使用的是 aDateTimeFormatterBuilder
及其appendPattern
方法,请以相同的方式使用单引号。或者使用它的appendLiteral
方法而不是单引号。
那么,我们如何在格式中加上单引号呢?两个单引号产生一个。双单引号是否在单引号内都没有关系:
DateTimeFormatter formatterWithSingleQuote = DateTimeFormatter.ofPattern("H mm'' ss\"");
System.out.println(LocalTime.now(ZoneId.of("Europe/London")).format(formatterWithSingleQuote));
10 28' 34"
DateTimeFormatter formatterWithSingleQuoteInsideSingleQuotes
= DateTimeFormatter.ofPattern("hh 'o''clock' a, zzzz", Locale.ENGLISH);
System.out.println(ZonedDateTime.now(ZoneId.of("America/Los_Angeles"))
.format(formatterWithSingleQuoteInsideSingleQuotes));
太平洋夏令时间凌晨 2 点
上面的所有格式化程序也可以用于解析。例如:
LocalTime time = LocalTime.parse("16 43' 56\"", formatterWithSingleQuote);
System.out.println(time);
16:43:56
SimpleDateFormat
近 10 年前提出这个问题时使用的类是出了名的麻烦且早已过时。我建议您改用 java.time,这是现代 Java 日期和时间 API。这就是为什么我要证明这一点。
链接