Java日期格式-包括附加字符

t1qtbnec  于 2022-12-21  发布在  Java
关注(0)|答案(5)|浏览(106)

在Java中有没有类似于php date()样式的格式?我的意思是,在php中我可以反斜杠转义字符,让它们按字面意思处理。也就是说,yyyy \y\e\a\r将变成2010年。我在Java中没有找到类似的东西,所有的例子都只处理内置的日期格式。
具体来说,我将处理JCalendar日期选取器及其dateFormatString属性。
我需要它,因为在我的语言环境中,需要用日期格式写各种各样的附加内容,比如d.(表示天)在天之后,m.(表示年)在年之后,等等。
在最坏的情况下,我可以使用字符串替换或regexp,但也许有一个更简单的方法?

l7mqbcuq

l7mqbcuq1#

当然,在SimpleDateFormat中可以包含文字字符串:
在日期和时间模式字符串中,从'A'到'Z'以及从'a'到'z'的无引号字母被解释为表示日期或时间字符串组成部分的模式字母。可以使用单引号(')将文本引起来以避免解释。“''”表示单引号。不解释所有其他字符;它们只是在格式化过程中复制到输出字符串中,或者在解析过程中与输入字符串匹配。

"hh 'o''clock' a, zzzz"    12 o'clock PM, Pacific Daylight Time
koaltpgm

koaltpgm2#

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

DateTimeFormatter.ofPattern("yyyy 'year'");
bq8i3lrv

bq8i3lrv3#

Java.时间

已经是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 year
2010 year
2019 year

如果您使用的是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:00 AM,太平洋夏令时
以上所有的格式化程序都可以用于解析。例如:

LocalTime time = LocalTime.parse("16 43' 56\"", formatterWithSingleQuote);
    System.out.println(time);

十六点四十三分五十六秒
大约10年前提出这个问题时使用的SimpleDateFormat类是出了名的麻烦,而且早就过时了。我建议您改用java.time,这是现代Java日期和时间API。这就是我演示它的原因。

链接

toiithl6

toiithl64#

您可以按照java.util.Formatter中的说明使用String.format:

Calendar c = ...;
String s = String.format("%tY year", c);
// -> s == "2010 year" or whatever the year actually is
t8e9dugd

t8e9dugd5#

java.text.SimpleDateFormat

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

您将在此处获得更多信息link text

相关问题