我需要以类似于星期三,一月9日
的形式打印出一个DateTime
对象,其中日期自动获取正确的后缀,例如1月2日将变为一月2日
。如何获得这样的DateTimeFormatter
对象?
Joda不支持此功能,但是在一定程度上,你可以使用ICU库,因为它包含本地化规则来格式化序数:
import com.ibm.icu.text.RuleBasedNumberFormat;
import com.ibm.icu.text.SimpleDateFormat;
...
SimpleDateFormat sdf =
new SimpleDateFormat("EEEE, MMMM d", Locale.ENGLISH);
sdf.setNumberFormat(
new RuleBasedNumberFormat(
Locale.ENGLISH, RuleBasedNumberFormat.ORDINAL));
System.out.println(sdf.format(new Date()));
String dayOfMonth = now.dayOfMonth().getAsText();
String suffix = "";
if(dayOfMonth.endsWith("1")) suffix = "st";
if(dayOfMonth.endsWith("2")) suffix = "nd";
if(dayOfMonth.endsWith("3")) suffix= "rd";
if(dayOfMonth.endsWith("0") || dayOfMonth.endsWith("4") || dayOfMonth.endsWith("5") || dayOfMonth.endsWith("6")
|| dayOfMonth.endsWith("7") || dayOfMonth.endsWith("8") || dayOfMonth.endsWith("9")) suffix = "th";
我不喜欢使用另一个库的解决方案,所以我使用正则表达式预处理字符串并删除序数后缀来解决这个问题。
val dateString1 = "6th December 2016"
dateString1.replaceFirst("^(\\d+).*? (\\w+ \\d+)", "$1 $2")
val dtf = DateTimeFormat.forPattern("dd MMMM yyyy").withLocale(Locale.ENGLISH)
val d1 = dtf.parseLocalDate(cured)
现在d1应该是d1: org.joda.time.LocalDate = 2016-12-06