Class Cosmo
A thin, ergonomic layer over ICU (reached through ICU4J). It bundles no locale data of its own — every result comes straight from ICU. Construct once per locale and reuse.
-
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionA new Cosmo with likely subtags added ("en"→"en_Latn_US").bestMatch(Collection<String> supported) The supported locale that best serves this Cosmo's locale, using CLDR language-distance data — e.g.Localised calendar name ("buddhist"→"Buddhist Calendar").compact(double value) Compact notation (1200→"1.2K").Compact notation;"full"/"long"width gives"1.2 thousand".intLocale-aware comparison of two strings (negative / zero / positive).intLocale-aware comparison with optional collation tailoring —numeric(boolean) andcaseFirst("upper"/"lower"/"false").booleanconfusable(String a, String b) Whether two strings are visually confusable ("paypal"vs a Cyrillic"раураl") per UTS #39.booleanLocale-aware substring test ignoring case and accents.booleanLocale-aware substring test with an explicit sensitivity.booleanLocale-aware substring test (accents/case can be ignored).country()Localised name of this locale's own region.Localised country/region name ("AU"→"Australia").currency()Localised name of thecurrencymodifier's currency.Localised currency name ("AUD"→"Australian Dollar").Localised currency name (default) or symbol.Seedate(Date, String).Format just the date part of a moment (short width).Format just the date part of a moment.Format a moment range with medium-width dates ("Feb 2 – 5, 2020").Format a moment range; supports the documented width combinations only.Text direction of this locale:"rtl"or"ltr".Text direction of a language:"rtl"or"ltr".displayName(String type, String code) Generic localised display name — one entry point over the dedicated lookups.duration(double seconds) Format an undirected duration in seconds as the clock form ("339:17:20").duration(double seconds, boolean withWords) Format an undirected duration in seconds.Format a multi-unit duration map with abbreviated units ("3 hr, 5 min").Format a multi-unit duration ({hours: 3, minutes: 5}→"3 hours, 5 minutes"withwithWords).Truncate to at mostmaxGraphemesgraphemes on a word boundary.Truncate to at mostmaxGraphemesgraphemes with a custom ellipsis.flag()Country flag emoji for this locale's region (""when it has none).Country flag emoji for a region ("AU"→"🇦🇺").formatMoment(Date value, String pattern) Format a moment with a raw ICU pattern ("yyyy-MM-dd").formatMoment(Date value, String pattern, String calendar) Format a moment with a raw ICU pattern, forcing a calendar ("gregorian", …).static CosmofromAcceptLanguage(String header) Builds a Cosmo from an HTTPAccept-Languageheader.static CosmofromAcceptLanguage(String header, Modifiers modifiers) Builds a Cosmo from an HTTPAccept-Languageheader, picking the best-quality tag.static CosmofromAcceptLanguage(String header, Collection<String> supported) Negotiating variant offromAcceptLanguage(String, Collection, Modifiers).static CosmofromAcceptLanguage(String header, Collection<String> supported, Modifiers modifiers) Builds a Cosmo for the supported locale that best serves an HTTPAccept-Languageheader, negotiated with CLDR language-distance data (seebestMatch(java.util.Collection<java.lang.String>)).static CosmofromSubtags(Subtags subtags) Builds a Cosmo from locale subtags, e.g.static CosmofromSubtags(Subtags subtags, Modifiers modifiers) Builds a Cosmo from locale subtags instead of a string.Read a value from an ICU resource bundle, falling back locale → language → root.indexBuckets(Collection<String> names) Group strings under locale-correct index headers (A–Z in en, 가나다 in ko, あかさ in ja, with the right under/overflow buckets).join(Collection<String> items) Join a list the locale's way ("A, B, and C").join(Collection<String> items, String type) Join a list;typeisconjunction(and),disjunction(or), orunit.join(Collection<String> items, String type, String width) Join a list the locale's way with an explicit type and width.language()Localised name of this locale's own language.Localised language name ("en"→"English").Locale-aware lower-casing.Format an ICU MessageFormat pattern with positional ({0}) placeholders.Format an ICU MessageFormat pattern with named placeholders.Format a date and/or time using the locale's conventions.money(double value) Formats a monetary value using thecurrencymodifier (inferred from the region when the locale has one).Formats a monetary value in the given ISO 4217 currency.Formats a monetary value.Formats a monetary value; seenumber(double, Map)for the options.moneyRange(double start, double end) Format a monetary range with thecurrencymodifier (""if none).moneyRange(double start, double end, String code) Format a monetary range ("$3.00 – $5.00").Localised month names (full width), following the active calendar.monthNames(String width) Localised month names, following the active calendar (e.g.number(double value) Format a number with the locale's default decimal format.Format a number with optional portable controls —minimumIntegerDigits,minimum/maximumFractionDigits,minimum/maximumSignificantDigits,roundingMode,roundingIncrement,useGrouping.numberRange(double start, double end) Format a numeric range ("3–5").ordinal(long number) Ordinal text (1→"1st").Parse a short-width localised date.Parse a localised date written at the given width (short…full).parseMoment(String text, String pattern) Parse a moment with a raw ICU pattern (the inverse offormatMoment(java.util.Date, java.lang.String)).com.ibm.icu.util.CurrencyAmountparseMoney(String text) Parse a localised monetary string ("$12.30"→ 12.3 USD).doubleparseNumber(String text) Parse a localised number ("1.234,56"in de →1234.56).percentage(double value) Format a fraction as a percentage (0.2→"20%").percentage(double value, int precision) Format a fraction as a percentage with at mostprecisionfraction digits.percentage(double value, int precision, Map<String, Object> options) Format a fraction as a percentage; seenumber(double, Map)for the options.personName(Map<String, String> fields) Format a person's name with medium length and formal formality.Locale-aware person-name formatting from CLDR person-name data: surname-first locales (ja/zh/hu), locale-correct initials and spacing, formality variants — zero hardcoded rules.pluralCategory(double value) The LDML cardinal plural category for a value (1→"one").pluralCategory(double value, boolean ordinal) The LDML plural category;ordinaluses ordinal rules (1st/2nd/3rd …).Wrap text in the locale's quotation marks (“x”in en,«x»in fa).relativeDuration(double amount, String unit) Directed duration, always numeric ((-3, "day")→"3 days ago").relativeDuration(double amount, String unit, String numeric) Render a directed duration.relativeDurationBetween(Date target) Directed duration between a moment and now, largest sensible unit, word forms allowed.relativeDurationBetween(Date target, Date reference) Directed duration between two moments ("in 5 days","3 days ago").relativeDurationBetween(Date target, Date reference, String numeric) Directed duration between two moments, computed astarget − reference(referencedefaults to now) and rendered in the largest sensible unit.A new Cosmo with likely subtags removed ("en_Latn_US"→"en").Romanise text ("Москва"→"Moskva"); shorthand forAny-Latin.scientific(double value) Scientific notation (12345→"1.2345E4").script()Localised name of this locale's own script (""when it has none).Localised script name ("Hans"→"Simplified").sort(Collection<String> items) A new list sorted by the locale's collation rules.A new sorted list with optional collation tailoring (seecompare(String, String, Map)).spellout(double number) Spell a number out (42→"forty-two").splitGraphemes(String text) Split text into grapheme clusters (combining marks / emoji stay intact).splitSentences(String text) Split text into sentences using the locale's boundary rules.splitWords(String text) Split text into words (drops whitespace/punctuation).supportedValues(String key) Values the runtime's ICU supports forkey(e.g. all IANA time zones).booleansuspicious(String text) Whether a string fails ICU's default spoof checks (mixed scripts, restriction level, invisible characters) per UTS #39.Returns a localised number symbol ("decimal","percent", …).Seetime(Date, String).Format just the time (clock) part of a moment (short width).Format just the time (clock) part of a moment.Display name of thetimeZonemodifier (or the system zone), long style.timeZoneName(String style) Display name of thetimeZonemodifier (or the system zone).transliterate(String text, String id) Run an ICU transform over the text — script conversion, romanisation, accent folding ("Any-Latin; Latin-ASCII"makes ASCII slugs).Format a measurement with a localised unit, full width.Format a measurement with a localised unit (2.19gigabytes).Locale-aware upper-casing (e.g.Localised weekday names (full width), Sunday first (ICU symbol order).weekdayNames(String width) Localised weekday names, Sunday first (ICU symbol order).weekInfo()Week conventions of the locale's region: first day, minimal days, and — unlike the Python port — the weekend days, via ICU's region week data.
-
Field Details
-
locale
Canonical ICU locale id, e.g."en_AU". -
subtags
Parsed language / script / region subtags. -
modifiers
Resolved modifiers (calendar / currency / timeZone).
-
-
Constructor Details
-
Cosmo
Builds a Cosmo for the given locale with no modifier overrides. -
Cosmo
- Parameters:
locale- BCP-47 or underscore locale id (en_AU,fa-IR,en_AU@calendar=buddhist).null/blank falls back to the JVM's default locale.modifiers- optionalcalendar,currencyandtimeZoneoverrides;nullfields are derived from the locale.
-
-
Method Details
-
fromSubtags
Builds a Cosmo from locale subtags, e.g.new Subtags("en", "", "AU"). -
fromSubtags
Builds a Cosmo from locale subtags instead of a string. -
fromAcceptLanguage
Builds a Cosmo from an HTTPAccept-Languageheader. -
fromAcceptLanguage
Builds a Cosmo from an HTTPAccept-Languageheader, picking the best-quality tag. -
fromAcceptLanguage
Negotiating variant offromAcceptLanguage(String, Collection, Modifiers). -
fromAcceptLanguage
public static Cosmo fromAcceptLanguage(String header, Collection<String> supported, Modifiers modifiers) Builds a Cosmo for the supported locale that best serves an HTTPAccept-Languageheader, negotiated with CLDR language-distance data (seebestMatch(java.util.Collection<java.lang.String>)). Falls back to the first supported locale. -
get
Read a value from an ICU resource bundle, falling back locale → language → root. -
language
Localised name of this locale's own language. -
language
Localised language name ("en"→"English"). -
country
Localised name of this locale's own region. -
country
Localised country/region name ("AU"→"Australia"). -
script
Localised name of this locale's own script (""when it has none). -
script
Localised script name ("Hans"→"Simplified").Uses the contextual CLDR
Scriptstable like the PHP port and JS'sIntl.DisplayNames. ICU4J only exposes that table through the deprecatedgetDisplayScriptInContext; every non-deprecated API returns the stand-alone variant ("Simplified Han") and would disagree with the other three ports. -
calendar
Localised calendar name ("buddhist"→"Buddhist Calendar"). -
direction
Text direction of this locale:"rtl"or"ltr". -
direction
Text direction of a language:"rtl"or"ltr".Script-based (via likely-subtags maximisation), so minority RTL languages with no locale-level layout data are detected too.
-
flag
Country flag emoji for this locale's region (""when it has none). -
flag
Country flag emoji for a region ("AU"→"🇦🇺"). Pure codepoint math. -
currency
Localised name of thecurrencymodifier's currency. -
currency
Localised currency name ("AUD"→"Australian Dollar"). -
currency
Localised currency name (default) or symbol.- Parameters:
code- ISO 4217 code;nullfalls back to thecurrencymodifier.symbol- return the disambiguated symbol ("A$") instead of the name.strict- throw on an unknown code instead of echoing it back.
-
number
Format a number with the locale's default decimal format. -
number
Format a number with optional portable controls —minimumIntegerDigits,minimum/maximumFractionDigits,minimum/maximumSignificantDigits,roundingMode,roundingIncrement,useGrouping. The JS-only options (signDisplay,notation, …) are accepted but ignored. -
percentage
Format a fraction as a percentage (0.2→"20%"). -
percentage
Format a fraction as a percentage with at mostprecisionfraction digits. -
percentage
Format a fraction as a percentage; seenumber(double, Map)for the options. -
money
Formats a monetary value using thecurrencymodifier (inferred from the region when the locale has one).- Returns:
- the formatted amount, or
""when no currency is available.
-
money
Formats a monetary value in the given ISO 4217 currency. -
money
Formats a monetary value.- Parameters:
code- ISO 4217 code;nullfalls back to thecurrencymodifier.precision- exact fraction digits, ornullfor the currency's default.strict- throw instead of returning""when no currency is available.
-
money
public String money(double value, String code, Integer precision, boolean strict, Map<String, Object> options) Formats a monetary value; seenumber(double, Map)for the options. -
symbol
Returns a localised number symbol ("decimal","percent", …).Accepts any
DecimalFormatSymbolsname (case-insensitive; the_symbol/_separator/_signsuffixes and separators are ignored). -
unit
Format a measurement with a localised unit, full width. -
unit
Format a measurement with a localised unit (2.19gigabytes).- Parameters:
category- informational grouping (e.g."digital"); not required by ICU.unit- ICU unit identifier, e.g."gigabyte","celsius","mile-per-hour".width-full/long→ wide,medium→ short,short→ narrow.
-
scientific
Scientific notation (12345→"1.2345E4"). -
compact
Compact notation (1200→"1.2K"). -
compact
Compact notation;"full"/"long"width gives"1.2 thousand". -
ordinal
Ordinal text (1→"1st"). Uses ICU RBNF. -
spellout
Spell a number out (42→"forty-two"). Uses ICU RBNF. -
duration
Format an undirected duration in seconds as the clock form ("339:17:20"). -
duration
Format an undirected duration in seconds.- Parameters:
withWords- spell the units out where the locale's RBNF has a%with-wordsruleset. Directed ("3 days ago") form:relativeDuration(double, String).
-
duration
Format a multi-unit duration map with abbreviated units ("3 hr, 5 min"). -
duration
Format a multi-unit duration ({hours: 3, minutes: 5}→"3 hours, 5 minutes"withwithWords). Accepted units: years, months, weeks, days, hours, minutes, seconds, milliseconds. -
moment
Format a date and/or time using the locale's conventions.- Parameters:
dateWidth- / timeWidth:none/short/medium/long/full.
-
moment
-
date
Format just the date part of a moment (short width). -
date
Format just the date part of a moment. -
date
Seedate(Date, String). -
time
Format just the time (clock) part of a moment (short width). -
time
Format just the time (clock) part of a moment. -
time
Seetime(Date, String). -
formatMoment
Format a moment with a raw ICU pattern ("yyyy-MM-dd"). -
formatMoment
Format a moment with a raw ICU pattern, forcing a calendar ("gregorian", …). -
dateRange
Format a moment range with medium-width dates ("Feb 2 – 5, 2020"). -
dateRange
Format a moment range; supports the documented width combinations only. -
compare
Locale-aware comparison of two strings (negative / zero / positive). -
compare
Locale-aware comparison with optional collation tailoring —numeric(boolean) andcaseFirst("upper"/"lower"/"false"). -
sort
A new list sorted by the locale's collation rules. -
sort
A new sorted list with optional collation tailoring (seecompare(String, String, Map)). -
contains
Locale-aware substring test ignoring case and accents. -
contains
Locale-aware substring test with an explicit sensitivity. -
contains
public boolean contains(String haystack, String needle, String sensitivity, Map<String, Object> options) Locale-aware substring test (accents/case can be ignored).- Parameters:
sensitivity-base(ignore case & accents),accent,case, orvariant(exact).
-
splitGraphemes
Split text into grapheme clusters (combining marks / emoji stay intact). -
splitWords
Split text into words (drops whitespace/punctuation). -
splitSentences
Split text into sentences using the locale's boundary rules. -
ellipsize
Truncate to at mostmaxGraphemesgraphemes on a word boundary. -
ellipsize
Truncate to at mostmaxGraphemesgraphemes with a custom ellipsis. -
message
Format an ICU MessageFormat pattern with named placeholders. -
message
Format an ICU MessageFormat pattern with positional ({0}) placeholders. -
pluralCategory
The LDML cardinal plural category for a value (1→"one"). -
pluralCategory
The LDML plural category;ordinaluses ordinal rules (1st/2nd/3rd …). -
join
Join a list the locale's way ("A, B, and C"). -
join
Join a list;typeisconjunction(and),disjunction(or), orunit. -
join
Join a list the locale's way with an explicit type and width. -
quote
Wrap text in the locale's quotation marks (“x”in en,«x»in fa). -
relativeDuration
Directed duration, always numeric ((-3, "day")→"3 days ago"). -
relativeDuration
Render a directed duration.- Parameters:
amount- signed — negative = past ("… ago"), positive = future ("in …").unit-second/minute/hour/day/week/month/quarter/year.numeric-"always"("1 day ago") or"auto"("yesterday"— ICU4J exposes the word forms the Python port can't reach).
-
relativeDurationBetween
Directed duration between a moment and now, largest sensible unit, word forms allowed. -
relativeDurationBetween
Directed duration between two moments ("in 5 days","3 days ago"). -
relativeDurationBetween
Directed duration between two moments, computed astarget − reference(referencedefaults to now) and rendered in the largest sensible unit. -
numberRange
Format a numeric range ("3–5"). -
moneyRange
Format a monetary range with thecurrencymodifier (""if none). -
moneyRange
Format a monetary range ("$3.00 – $5.00").""if no currency. -
addLikelySubtags
A new Cosmo with likely subtags added ("en"→"en_Latn_US"). -
removeLikelySubtags
A new Cosmo with likely subtags removed ("en_Latn_US"→"en"). -
monthNames
Localised month names (full width), following the active calendar. -
monthNames
Localised month names, following the active calendar (e.g. Persian forfa_IR). -
weekdayNames
Localised weekday names (full width), Sunday first (ICU symbol order). -
weekdayNames
Localised weekday names, Sunday first (ICU symbol order). -
weekInfo
Week conventions of the locale's region: first day, minimal days, and — unlike the Python port — the weekend days, via ICU's region week data. -
timeZoneName
Display name of thetimeZonemodifier (or the system zone), long style. -
timeZoneName
Display name of thetimeZonemodifier (or the system zone).- Parameters:
style-long/short/longOffset/shortOffset/longGeneric/shortGeneric.
-
displayName
Generic localised display name — one entry point over the dedicated lookups.- Parameters:
type-language,region,script,calendar, orcurrency.
-
supportedValues
Values the runtime's ICU supports forkey(e.g. all IANA time zones).Supported keys:
timeZone,collation,numberingSystem,unit,currency,calendar. ICU4J can enumerate the last two — an enumeration PyICU lacks, so the Python port raises for them. -
bestMatch
The supported locale that best serves this Cosmo's locale, using CLDR language-distance data — e.g.en_AUpicksen-GBoveren-US, andsr-Latnis served better byhrthan bysr-Cyrl. Falls back to the first supported locale when nothing matches well.- Returns:
- the matching entry exactly as it appears in
supported.
-
transliterate
Run an ICU transform over the text — script conversion, romanisation, accent folding ("Any-Latin; Latin-ASCII"makes ASCII slugs).- Parameters:
id- a compound ICU transliterator id; seesupportedValues("transliterator")for the building blocks.
-
romanize
Romanise text ("Москва"→"Moskva"); shorthand forAny-Latin. -
confusable
Whether two strings are visually confusable ("paypal"vs a Cyrillic"раураl") per UTS #39. Locale-independent. -
suspicious
Whether a string fails ICU's default spoof checks (mixed scripts, restriction level, invisible characters) per UTS #39. -
indexBuckets
Group strings under locale-correct index headers (A–Z in en, 가나다 in ko, あかさ in ja, with the right under/overflow buckets). Buckets keep the locale's label order; empty buckets are omitted; items are collated. -
parseNumber
Parse a localised number ("1.234,56"in de →1234.56). -
parseMoney
Parse a localised monetary string ("$12.30"→ 12.3 USD).- Returns:
- an ICU
CurrencyAmount:getNumber()andgetCurrency().
-
parseDate
Parse a short-width localised date. -
parseDate
Parse a localised date written at the given width (short…full). -
parseMoment
Parse a moment with a raw ICU pattern (the inverse offormatMoment(java.util.Date, java.lang.String)). -
personName
Format a person's name with medium length and formal formality. -
personName
Locale-aware person-name formatting from CLDR person-name data: surname-first locales (ja/zh/hu), locale-correct initials and spacing, formality variants — zero hardcoded rules.ICU technology preview: the underlying API may shift between ICU releases; this method's own surface will stay stable.
- Parameters:
fields- name fields —given,surname, and optionallytitle,given2,surname2,generation,credentials, pluslocale: the locale of the name itself (e.g."ja"so 山田/太郎 renders surname-first).length-short/medium/long.formality-formal/informal.
-
upper
Locale-aware upper-casing (e.g. Turkish dotted/dotless I). -
lower
Locale-aware lower-casing.
-