SpringBoot Thymeleaf ordinal numbers

ぃ、小莉子 提交于 2019-12-10 18:27:56

问题


I have read a few good posts like this one which explain the method of receiving ordinal numbers when given an int.

Now, I have a LocalDate object and I can format my dates using any of the DateTimeFormat patterns in my Thymeleaf template. Example being something like:

<strong th:text="${item.date} ? ${#temporals.format(item.date, 'dd')}"></strong>

Question: How can I or perhaps what is the best way of achieving similar results to the post I linked to above in Thymeleaf.

I am not an experienced Java developer so it would be very helpful if you be as thorough as you possibly can with explaining the answer.


回答1:


Inside the Thymeleaf's template you can use static fields (and functions), so in you case it will looks like that:
1) Code from the question you related (I just modified it a little bit) :

package your.packagename;
// http://code.google.com/p/guava-libraries
import static com.google.common.base.Preconditions.*;

public class YourClass {

    public static String getDayOfMonthSuffix(String num) {
        Integer n = Integer.valueOf(num == null ? "1" : num);
        checkArgument(n >= 1 && n <= 31, "illegal day of month: " + n);
        if (n >= 11 && n <= 13) {
            return "th";
        }
        switch (n % 10) {
            case 1:  return "st";
            case 2:  return "nd";
            case 3:  return "rd";
            default: return "th";
        }
    }
}

2) Call it inside the view :

<strong th:text="${#temporals.format(item.date, 'dd') + T(your.packagename.YourClass).getDayOfMonthSuffix(#temporals.format(item.date, 'dd'))}"></strong>


来源:https://stackoverflow.com/questions/36936910/springboot-thymeleaf-ordinal-numbers

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