Page 1 of 1

groovy ordinal suffix (i.e. "1st" "2nd" "3rd"...etc)

Posted: 30 Aug 2021, 03:41
by xaeiou
Sometimes I want to add an ordinal suffix to a title - most often in dates, but it can be in other fields.

I've played around with a few ways to do this, but not yet found an elegant way to do it in Groovy - but then I'm still a Groovy newbie :D

Specifically for dates, I found this pretty good summary of things that can be done:

https://rmr.fandom.com/wiki/Groovy_Date ... Formatting

But still no mention in there of ordinal suffix support in Groovy.

To give a specific example, let's say I have this in my format expression:

Code: Select all

{airdate.format('d MMMM yyyy')}    
Which will output a date in the format "1 July 1978"

Can anyone suggest an elegant way in Groovy to change this to "1st July 1978"?

Re: groovy ordinal suffix (eg "20th" "31st" etc)

Posted: 30 Aug 2021, 04:13
by rednoah
There does not seem to be a built-in way to get 1st 2nd 3rd date formatting:
https://docs.oracle.com/en/java/javase/ ... l#patterns


AFAICT, there's no easy way... You can write your own code, but you're definitely gonna blow up the number of lines 10-fold for that and thus won't be elegant.

Re: groovy ordinal suffix (eg "20th" "31st" etc)

Posted: 30 Aug 2021, 05:54
by xaeiou
Thanks, as always your response is much appreciated, and I'll read through the fuller java documentation.

Googling around I see a few pre-made functions people have come up with in various languages (java included), and as you say they are 10+ lines to handle the basic cases and longer if you handle some corner cases or different locales.

A little ad-hoc post filebot scripting on the filenames works for me :)

Re: groovy ordinal suffix (i.e. "1st" "2nd" "3rd"...etc)

Posted: 30 Aug 2021, 06:17
by rednoah
Since we're already here, I might as well add my solution for the next guy to just copy & paste.

e.g.

Code: Select all

{
	airdate.format('d MMMM yyyy').replaceFirst(/\d+/) { d ->
		d =~ /11$|12$|13$/ ? d + 'th' : 
		d =~ /1$/ ? d + 'st' : 
		d =~ /2$/ ? d + 'nd' :
		d =~ /3$/ ? d + 'rd' :
		d + 'th'
	}
}

EDIT: Forgot about 11th / 12th / 13th in my first revision. :lol:

Re: groovy ordinal suffix (i.e. "1st" "2nd" "3rd"...etc)

Posted: 30 Aug 2021, 12:42
by xaeiou
That works great!

Also I can see how to use this as a template to integrate other functionality from a few bash scripts I have into my Groovy format file.

Thanks very much :D