Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 336
Hamster Avatar asked Feb 11 '26 15:02

Hamster


1 Answers

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>
like image 102
sanluck Avatar answered Feb 13 '26 05:02

sanluck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!