Java日期格式-包括其他字符
Java中是否有与php date()样式格式相同的格式?我的意思是,在php中,我可以反斜杠转义字符,让它们按字面意思处理。也就是说,yyyy\y\e\a\r将成为2010年。我在Java中没有发现任何类似的内容,所有示例都只处理内置的日期格式 特别是,我处理日期选择器及其dateFormatString属性Java日期格式-包括其他字符,java,date-format,Java,Date Format,Java中是否有与php date()样式格式相同的格式?我的意思是,在php中,我可以反斜杠转义字符,让它们按字面意思处理。也就是说,yyyy\y\e\a\r将成为2010年。我在Java中没有发现任何类似的内容,所有示例都只处理内置的日期格式 特别是,我处理日期选择器及其dateFormatString属性 我需要它,因为在我的语言环境中,它需要以日期格式编写各种附加内容,比如d。(天)天部分之后,m。(多年)多年后分手等等。在最坏的情况下,我可以使用字符串替换或regexp,但也许有更简单
我需要它,因为在我的语言环境中,它需要以日期格式编写各种附加内容,比如d。(天)天部分之后,m。(多年)多年后分手等等。在最坏的情况下,我可以使用字符串替换或regexp,但也许有更简单的方法?提前谢谢 您可以使用String.format,如中所述:
java.text.simpleDataFormat
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
String formattedDate = formatter.format(date);
您将在此处获得更多信息当然,您可以包括文字字符串:
在日期和时间模式字符串中,从“A”到“Z”以及从“A”到“Z”的无引号字母被解释为表示日期或时间字符串组件的模式字母。可以使用单引号(')引用文本以避免解释。“''”表示一个单引号。所有其他字符不被解释;它们只是在格式化期间复制到输出字符串中,或者在解析期间与输入字符串匹配
为了完整起见,Java 8的
DateTimeFormatter
还支持以下功能:
DateTimeFormatter.ofPattern("yyyy 'year'");
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));
刚刚运行时的输出:
如果您使用的是DateTimeFormatterBuilder
及其appendPattern
方法,请以相同的方式使用单引号。或者改用它的appendLiteral
方法,不使用单引号
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));
那么,我们如何在格式中添加单个报价?两个单引号产生一个。双单引号是否在单引号内并不重要:
DateTimeFormatter formatterWithSingleQuote = DateTimeFormatter.ofPattern("H mm'' ss\"");
System.out.println(LocalTime.now(ZoneId.of("Europe/London")).format(formatterWithSingleQuote));
10 28'34“
太平洋夏令时凌晨2点
上述所有格式化程序也可用于解析。例如:
LocalTime time = LocalTime.parse("16 43' 56\"", formatterWithSingleQuote);
System.out.println(time);
16:43:56
近10年前提出这个问题时使用的SimpleDateFormat
类是出了名的麻烦和过时的。我建议您使用java.time,现代java日期和时间API。这就是为什么我要演示它
链接
- 解释如何使用java.time
46'.
。第一个转义为第二个。仅供参考,最可怕的是Rouble一些日期时间类,如,和java.text.SimpleDateFormat
现在被java 8和更高版本中内置的类所取代。对于2019年或更高版本阅读本文的人来说,在几个答案中使用的SimpleDateFormat
类是出了名的麻烦和过时的。避免它。而是使用演示使用。
DateTimeFormatter formatterWithSingleQuote = DateTimeFormatter.ofPattern("H mm'' ss\"");
System.out.println(LocalTime.now(ZoneId.of("Europe/London")).format(formatterWithSingleQuote));
DateTimeFormatter formatterWithSingleQuoteInsideSingleQuotes
= DateTimeFormatter.ofPattern("hh 'o''clock' a, zzzz", Locale.ENGLISH);
System.out.println(ZonedDateTime.now(ZoneId.of("America/Los_Angeles"))
.format(formatterWithSingleQuoteInsideSingleQuotes));
LocalTime time = LocalTime.parse("16 43' 56\"", formatterWithSingleQuote);
System.out.println(time);