LocalDateFormatter 月份基数
LocalDateFormatter day of month cardinality
是否有用于 LocalDateFormatter 的格式模式来显示当月第几天的基数以及其他值?
比如我想打印2016年十一月一日,或者2017年二月二十七日。
提前致谢,
卢卡斯
正如 M. Prokhorov 已经说过的,这不是内置的。如果你只需要它用于英语语言环境,它应该不会太难,但是:
private static final String[] dayNumberNames = { null, "first", "second",
"third", // etc.
};
public static String formatMyWay(LocalDate date) {
String month = date.getMonth().toString();
month = month.substring(0, 1) + month.substring(1).toLowerCase(Locale.ENGLISH);
return "" + date.getYear() + ' ' + month + ' ' + dayNumberNames[date.getDayOfMonth()];
}
这会给你类似的东西
2017 February twenty-seventh
根据您的口味进行润色。
数组的初始 null
元素是为了补偿数组索引从 0 开始而天数从 1 开始的事实。
您可以使用 DateTimeFormatterBuilder
和
public DateTimeFormatterBuilder appendText(TemporalField field, Map<Long, String> textLookup)
采用 Map
的方法,用于查找字段的值。类似于:
static final Map<Long, String> ORDINAL_DAYS = new HashMap<>();
static
{
ORDINAL_DAYS.put(1, "First");
ORDINAL_DAYS.put(2, "Second");
... values for month days 1 .. 31
ORDINAL_DAYS.put(31, "Thirty-first");
}
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendText(ChronoField.YEAR)
.appendLiteral(' ')
.appendText(ChronoField.MONTH_OF_YEAR)
.appendLiteral(' ')
.appendText(ChronoField.DAY_OF_MONTH, ORDINAL_DAYS)
.toFormatter();
String formattedDate = formatter.format(date);
是否有用于 LocalDateFormatter 的格式模式来显示当月第几天的基数以及其他值?
比如我想打印2016年十一月一日,或者2017年二月二十七日。
提前致谢, 卢卡斯
正如 M. Prokhorov 已经说过的,这不是内置的。如果你只需要它用于英语语言环境,它应该不会太难,但是:
private static final String[] dayNumberNames = { null, "first", "second",
"third", // etc.
};
public static String formatMyWay(LocalDate date) {
String month = date.getMonth().toString();
month = month.substring(0, 1) + month.substring(1).toLowerCase(Locale.ENGLISH);
return "" + date.getYear() + ' ' + month + ' ' + dayNumberNames[date.getDayOfMonth()];
}
这会给你类似的东西
2017 February twenty-seventh
根据您的口味进行润色。
数组的初始 null
元素是为了补偿数组索引从 0 开始而天数从 1 开始的事实。
您可以使用 DateTimeFormatterBuilder
和
public DateTimeFormatterBuilder appendText(TemporalField field, Map<Long, String> textLookup)
采用 Map
的方法,用于查找字段的值。类似于:
static final Map<Long, String> ORDINAL_DAYS = new HashMap<>();
static
{
ORDINAL_DAYS.put(1, "First");
ORDINAL_DAYS.put(2, "Second");
... values for month days 1 .. 31
ORDINAL_DAYS.put(31, "Thirty-first");
}
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendText(ChronoField.YEAR)
.appendLiteral(' ')
.appendText(ChronoField.MONTH_OF_YEAR)
.appendLiteral(' ')
.appendText(ChronoField.DAY_OF_MONTH, ORDINAL_DAYS)
.toFormatter();
String formattedDate = formatter.format(date);