使用序数转换日期(第11,22等) [英] Convert date with ordinal numbers (11th, 22nd, etc.)
问题描述
如何转换具有以下格式的日期
How to convert a date having the following format
2015年9月22日,上午10:39:42
September 22nd 2015, 10:39:42 am
到
09/22/2015 10:39:42
09/22/2015 10:39:42
Java 8中的
?
in Java 8?
我当前的代码:
String value = "September 22nd 2015, 10:39:42 am";
String format = "dd/MM/yyyy HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
Date date = sdf.parse(value);
System.out.println(date);
System.out.println(sdf.format(date));
}
catch (ParseException ex) {
ex.printStackTrace();
}
推荐答案
格式的棘手部分是处理序数(如 22nd
),即处理正确的后缀。没有内置模式。为此,我们必须在 DateTimeFormatterBuilder
的帮助下构建我们自己的 DateTimeFormatter
。
The tricky part of the format is to handle ordinal numbers (like 22nd
), i.e. handle the right suffix. There is not built-in pattern. For this, we have to build our own DateTimeFormatter
with the help of DateTimeFormatterBuilder
.
DateTimeFormatterBuilder
有一个方法 appendText(field,textLookup)
其目标是在给定的映射中查找读取文本,并将其替换为与此值关联的键。这意味着我们需要使用相应的后缀构建所有可能日期(1到31)的地图。
DateTimeFormatterBuilder
has a method appendText(field, textLookup)
whose goal is to look for the read text in the given map and replace it by the key associated to this value. This means we need to build a Map of all possibles days (1 to 31) with their corresponding suffix.
我从这个答案。
我们还需要确保解析AM / PM标识符忽略case(默认情况下,它以大写形式查找AM和PM,但是您的大小写为小写)。这是通过调用 <来完成的。在为此附加模式之前code> parseCaseInsensitive 。
We also need to make sure to parse the AM/PM identifier ignoring the case (by default, it looks for AM and PM in uppercase but yours are in lowercase). This is done by calling parseCaseInsensitive
before appending the pattern for this.
private static final Map<Long, String> DAYS_LOOKUP =
IntStream.rangeClosed(1, 31).boxed().collect(toMap(Long::valueOf, i -> getOrdinal(i)));
public static void main(String[] args) throws Exception {
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMMM")
.appendLiteral(" ")
.appendText(ChronoField.DAY_OF_MONTH, DAYS_LOOKUP)
.appendLiteral(" ")
.appendPattern("yyyy")
.appendLiteral(", ")
.appendPattern("hh")
.appendLiteral(":")
.appendPattern("mm")
.appendLiteral(":")
.appendPattern("ss")
.appendLiteral(" ")
.parseCaseInsensitive()
.appendPattern("a")
.toFormatter(Locale.ENGLISH);
LocalDateTime dateTime = formatter.parse("September 22nd 2015, 10:39:42 am", LocalDateTime::from);
String text = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss").format(dateTime);
System.out.println(text);
}
private static String getOrdinal(int n) {
if (n >= 11 && n <= 13) {
return n + "th";
}
switch (n % 10) {
case 1: return n + "st";
case 2: return n + "nd";
case 3: return n + "rd";
default: return n + "th";
}
}
这篇关于使用序数转换日期(第11,22等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!