在Java中有没有等同于php date()样式格式化的东西?我的意思是,在php中,我可以使用反斜杠-转义字符来逐字处理它们。即yyyy \y\e\a\r将成为2010年。我在Java中找不到类似的东西,所有的例子都只处理内置的日期格式。
特别是,我要处理JCalendar日期选择器及其dateFormatString属性。
我之所以需要它,是因为在我的语言环境中,它需要以日期格式编写各种附加内容,比如d. (表示天)在days part之后,m. (对于年份)在years之后等等。在最坏的情况下,我可以使用字符串替换或regexp,但也许有一种更简单的方法?提前感谢!
发布于 2010-01-26 16:05:20
当然,使用SimpleDateFormat可以包含文字字符串:
在日期和时间模式字符串中,从'A‘到'Z’以及从'a‘到'z’的无引号字母被解释为表示日期或时间字符串组成部分的模式字母。文本可以用单引号(')引起来,以避免解释。"''“表示单引号。所有其他字符都不会被解释;它们只是在格式化过程中复制到输出字符串中,或者在解析过程中与输入字符串匹配。
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
发布于 2018-04-05 16:29:04
为了完整起见,Java8的DateTimeFormatter
也支持这样:
DateTimeFormatter.ofPattern("yyyy 'year'");
发布于 2019-10-04 17:36:15
java.time
已经是Mark Jeronimus said it了。我正在更多地充实它。只需将要打印的文本直接放在单引号内即可。
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年2010年2019年
如果您正在使用DateTimeFormatterBuilder
及其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));
凌晨02点,太平洋夏令时
上面所有的格式化程序也可以用于解析。例如:
LocalTime time = LocalTime.parse("16 43' 56\"", formatterWithSingleQuote);
System.out.println(time);
16:43:56
近10年前提出这个问题时使用的SimpleDateFormat
类是出了名的麻烦,而且早就过时了。我建议您改用java.time,这是现代的Java date and time API。这就是为什么我要演示这一点。
链接
解释如何使用java.time.
的
https://stackoverflow.com/questions/2138085
复制相似问题