Joda DateTimeFormat with proper number suffix

情到浓时终转凉″ 提交于 2020-01-13 13:52:42

问题


I need to print a DateTime in the form of, for example, Wednesday, January 9th, where the day of month automatically gets the proper suffix, e.g. January 2 would be January 2nd. How can I get a DateTimeFormatter that does this?


回答1:


There is no support for this in Joda, but with some limitations, you can use the ICU library, since it includes localized rules for formatting ordinal numbers:

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()));

Note that you can only specify one NumberFormat instance for the SimpleDateFormat instance, so that this approach only works if the "day of month" is the only number in the date pattern. Adding "yyyy" to the date pattern will e.g. format the year as "2,013th".

The ICU classes interface with the Date and Calendar classes from the standard API, so if you really have to use Joda in the first place, you would have to create a java.util.Date from your Joda DateTime instance.




回答2:


In Joda, for simply getting the proper suffix for the day of month, something as simple as the following should be sufficient:

        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";



回答3:


I dont like the solution of using another library, so I solve this using a regular expression to preprocess the string and remove the ordinal suffix

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)

now d1 should be d1: org.joda.time.LocalDate = 2016-12-06



来源:https://stackoverflow.com/questions/14238246/joda-datetimeformat-with-proper-number-suffix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!