Ordinal dates?
Related mbostock/d3#495. TODO:
- [ ] Decide on localizable implementation. (Locale-defined function.)
- [x] Decide on directive. (
%o) - [ ] Implement formatting.
- [ ] Implement padding.
- [ ] Implement parsing.
- [ ] Test.
This implementation works in English:
var suffixes = ["th", "st", "nd", "rd"];
function suffix(number) {
var tail = number % 100;
return suffixes[(tail < 11 || tail > 13) && (tail % 10)] || suffixes[0];
}
However, it’s not clear how we should localize this behavior. Perhaps the locale definition can include a JavaScript function?
Also, we need to decide the appropriate directive. I think %o might be a good choice: “o” for “ordinal”, and lowercase like %d and %e.
I believe we only need an ordinal suffix for day-of-month, so the %o directive should include %d (i.e., you don’t need both, %d%o, to display a suffixed date). This way the locale definition has more flexibility about how the ordinal date is formatted, rather than requiring it to be a suffix. For example, you could have an English locale that writes out the long form of the date, such as “The Second of May”. That said, it should still support padding if appropriate, so %0o is the zero-padded ordinal date, such as "02nd".
For German locales it's just an added ".".
From my tests the implementation above doesn't work for the values 1, 2, 3. This does:
const ordinalSuffixes = ['th', 'st', 'nd', 'rd'];
function ordinalSuffix(number) {
const value = number % 100;
return ordinalSuffixes[(value - 20) % 10] || ordinalSuffixes[value] || ordinalSuffixes[0];
}
I was missing some parens. Added.
Ah nice. 👍
In Bulgarian the suffix changes with each day: 1 2ри 3ти 4ти 5ти 6ти 7ми 8ми 9ти 10ти 11ти 12ти 13ти 14ти 15ти 16ти 17ти 18ти 19ти 20ти 21ви 22ри 23ти 24ти 25ти 26ти 27ми 28ми 29ти 30ти 31ви (pronounced "pi", "mi", "ti", "bi"…) See also https://blazingbulgaria.wordpress.com/2012/06/15/ordinal-numbers-in-bulgarian/
Ref https://github.com/d3/d3-time-format/pull/12