98

Java中是否有等效于php date() 样式的格式?我的意思是,在 php 中,我可以使用反斜杠转义字符来对它们进行字面处理。即yyyy \y\e\a\r将变为2010 year。我在 Java 中没有发现任何类似的东西,所有示例都只处理内置日期格式。

特别是,我处理JCalendar日期选择器及其dateFormatString属性。

我需要它,因为在我的语言环境中,需要以日期格式编写各种附加内容,例如 d. (代表日)日后部分,m。(多年)多年后的一部分,依此类推。在最坏的情况下,我可以使用字符串替换或正则表达式,但也许有更简单的方法?提前致谢!

4

5 回答 5

178

当然,使用SimpleDateFormat您可以包含文字字符串:

在日期和时间模式字符串中,从 'A' 到 'Z' 和从 'a' 到 'z' 的不带引号的字母被解释为代表日期或时间字符串组件的模式字母。可以使用单引号 (') 引用文本以避免解释。"''" 表示单引号。不解释所有其他字符;它们只是在格式化期间复制到输出字符串中,或​​者在解析期间与输入字符串匹配。

 "hh 'o''clock' a, zzzz"    12 o'clock PM, Pacific Daylight Time
于 2010-01-26T08:05:19.513 回答
28

为了完整起见,Java 8DateTimeFormatter也支持这一点:

DateTimeFormatter.ofPattern("yyyy 'year'");
于 2018-04-05T08:29:03.690 回答
8

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。这就是为什么我要证明这一点。

链接

于 2019-10-04T09:36:15.197 回答
6

您可以使用java.util.Formatter 中记录的 String.format :

Calendar c = ...;
String s = String.format("%tY year", c);
// -> s == "2010 year" or whatever the year actually is
于 2010-01-26T07:56:21.373 回答
-4

java.text.SimpleDateFormat

SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); 
String formattedDate = formatter.format(date);

您将在此处获得更多信息链接文本

于 2010-01-26T08:02:32.900 回答