简体   繁体   中英

SpringBoot Thymeleaf ordinal numbers

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM