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

All about user-defined episode / movie / file name format expressions
Post Reply
xaeiou
Posts: 15
Joined: 22 Oct 2019, 06:24

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

Post 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"?
Last edited by xaeiou on 30 Aug 2021, 06:02, edited 1 time in total.
User avatar
rednoah
The Source
Posts: 22923
Joined: 16 Nov 2011, 08:59
Location: Taipei
Contact:

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

Post 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.
:idea: Please read the FAQ and How to Request Help.
xaeiou
Posts: 15
Joined: 22 Oct 2019, 06:24

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

Post 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 :)
User avatar
rednoah
The Source
Posts: 22923
Joined: 16 Nov 2011, 08:59
Location: Taipei
Contact:

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

Post 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:
:idea: Please read the FAQ and How to Request Help.
xaeiou
Posts: 15
Joined: 22 Oct 2019, 06:24

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

Post 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
Post Reply