public final class

Humanize

extends Object
java.lang.Object
   ↳ humanize.Humanize

Class Overview

Facility for adding a "human touch" to data. It is thread-safe and supports per-thread internationalization. Additionally provides a concise facade for access to Standard i18n Java APIs.

Summary

Public Methods
static String binaryPrefix(Number value)

Converts a given number to a string preceded by the corresponding binary International System of Units (SI) prefix.

static String binaryPrefix(Number value, Locale locale)

Same as binaryPrefix(Number) for the specified locale.

static String camelize(String text, Locale locale)

Same as camelize(String) for the specified locale.

static String camelize(String text, boolean capitalizeFirstChar)

Makes a phrase camel case.

static String camelize(String text)

Same as camelize(String, boolean) with capitalize to false.

static String camelize(String text, boolean capitalizeFirstChar, Locale locale)

Same as camelize(String, boolean) for the specified locale.

static String capitalize(String text, Locale locale)

Same as capitalize(String) for the specified locale.

static String capitalize(String text)

Capitalizes the given text smartly.

static DateFormat dateFormat(String pattern)

Returns a SimpleDateFormat instance for the current thread.

static DateFormat dateFormat(String pattern, Locale locale)

Same as dateFormat(String) for the specified locale.

static String decamelize(String words, String replacement)

Converts a camel case string into a human-readable name.

static String decamelize(String words)

Same as decamelize(String) defaulting to SPACE for replacement

static DecimalFormat decimalFormat(String pattern)

Returns a DecimalFormat instance for the current thread.

static DecimalFormat decimalFormat(String pattern, Locale locale)

Same as decimalFormat(String) for the specified locale.

static String duration(Number seconds, Constants.TimeStyle style)

Formats a number of seconds as hours, minutes and seconds.

static String duration(Number seconds, Constants.TimeStyle style, Locale locale)

Same as duration(Number, TimeStyle) for the specified locale.

static String duration(Number seconds, Locale locale)

Same as duration(Number) for the specified locale.

static String duration(Number seconds)

Formats a number of seconds as hours, minutes and seconds.

static String fixLength(String text, int charsNum, char paddingChar, boolean left)

Pads or truncates a string to a specified length.

static String fixLength(String text, int charsNum, char paddingChar)

Pads or truncates a string to a specified length.

static String format(Locale locale, String pattern, Object... args)

Same as #format(String, Object...) for the specified locale.

static String format(String pattern, Object... args)

Gets an ExtendedMessageFormat instance for the current thread with the given pattern and uses it to format a message with the specified arguments.

static String formatCurrency(Number value, Locale locale)

Same as formatCurrency(Number) for the specified locale.

static String formatCurrency(Number value)

Smartly formats the given number as a monetary amount.

static String formatDate(Date value, String pattern)

Formats a date according to the given pattern.

static String formatDate(Date value, Locale locale)

Same as formatDate(Date) for the specified locale.

static String formatDate(Date value)

Same as formatDate(int, Date) with SHORT style.

static String formatDate(int style, Date value)

Formats the given date with the specified style.

static String formatDate(Date value, String pattern, Locale locale)

Same as formatDate(Date, String) for the specified locale.

static String formatDate(int style, Date value, Locale locale)

Same as formatDate(int, Date) for the specified locale.

static String formatDateTime(int dateStyle, int timeStyle, Date value)

Formats the given date/time with the specified styles.

static String formatDateTime(int dateStyle, int timeStyle, Date value, Locale locale)

Same as formatDateTime(int, int, Date) for the specified locale.

static String formatDateTime(Date value, Locale locale)

Same as formatDateTime(Date) for the specified locale.

static String formatDateTime(Date value)

Formats the given date/time with SHORT style.

static String formatDecimal(Number value)

Formats the given number to the standard decimal format for the default locale.

static String formatDecimal(Number value, Locale locale)

Same as formatDecimal(Number) for the specified locale.

static String formatPercent(Number value, Locale locale)

Same as formatPercent(Number) for the specified locale.

static String formatPercent(Number value)

Formats the given ratio as a percentage.

static boolean lossyEquals(Locale locale, String source, String target)

Same as lossyEquals(String, String) for the specified locale.

static boolean lossyEquals(String source, String target)

Locale-sensitive string comparison for primary differences.

static String mask(String mask, String value)

Formats the given text with the mask specified.

static MaskFormat maskFormat(String mask)

Returns a MaskFormat instance for the current thread.

static MessageFormat messageFormat(String pattern, Locale locale)

Same as messageFormat(String) for the specified locale.

static MessageFormat messageFormat(String pattern)

Returns a MessageFormat instance for the current thread.

static String metricPrefix(Number value)

Converts a given number to a string preceded by the corresponding decimal multiplicative prefix.

static String metricPrefix(Number value, Locale locale)

Same as metricPrefix(Number) for the specified locale.

static String nanoTime(Number value)

Formats a number of nanoseconds as the proper ten power unit.

static String nanoTime(Number value, Locale locale)

Same as nanoTime(Number) for the specified locale.

static String naturalDay(int style, Date then, Locale locale)
Same as naturalDay(int, Date) with the given locale.
static String naturalDay(Date then, Locale locale)
Same as naturalDay(Date) with the given locale.
static String naturalDay(int style, Date then)
For dates that are the current day or within one day, return 'today', 'tomorrow' or 'yesterday', as appropriate.
static String naturalDay(Date then)
Same as naturalDay(int, Date) with DateFormat.SHORT style.
static String naturalTime(Date duration, TimeMillis precision, Locale locale)
static String naturalTime(Date reference, Date duration, Locale locale)
Same as naturalTime(Date, Date) for the specified locale.
static String naturalTime(Date reference, Date duration, long precision)
Computes both past and future relative dates with arbitrary precision.
static String naturalTime(Date reference, Date duration, TimeMillis precision, Locale locale)
static String naturalTime(Date duration)
Same as naturalTime(Date, Date) with current date as reference.
static String naturalTime(Date duration, long precision, Locale locale)
Same as naturalTime(Date, long) for the specified locale.
static String naturalTime(Date duration, TimeMillis precision)
static String naturalTime(Date reference, Date duration)
Computes both past and future relative dates.
static String naturalTime(Date duration, long precision)
Same as naturalTime(Date, Date, long) with current date as reference.
static String naturalTime(Date duration, Locale locale)
Same as naturalTime(Date) for the specified locale.
static String naturalTime(Date reference, Date duration, long precision, Locale locale)
Same as naturalTime(Date, Date, long) for the specified locale.
static String naturalTime(Date reference, Date duration, TimeMillis precision)
static String ordinal(Number value)
Converts a number to its ordinal as a string.
static String ordinal(Number value, Locale locale)
Same as ordinal(Number) for the specified locale.
static String oxford(Object[] items, int limit, String limitStr, Locale locale)
Same as oxford(Object[], int, String) for the specified locale.
static String oxford(Object[] items)

Converts a list of items to a human readable string.

static String oxford(Collection<?> items, int limit, String limitStr)

Converts a list of items to a human readable string with an optional limit.

static String oxford(Collection<?> items, Locale locale)
Same as oxford(Object[]) for the specified locale.
static String oxford(Object[] items, Locale locale)
Same as oxford(Object[]) for the specified locale.
static String oxford(Collection<?> items)

Converts a list of items to a human readable string.

static String oxford(Object[] items, int limit, String limitStr)

Converts a list of items to a human readable string with an optional limit.

static Pace pace(Number value, long interval)
Matches a pace (value and interval) with a logical time frame.
static String paceFormat(Number value, long interval, String one, String many, String none)
Matches a pace (value and interval) with a logical time frame.
static String paceFormat(Number value, long interval)
Matches a pace (value and interval) with a logical time frame.
static String paceFormat(Locale locale, Number value, long interval)
Same as paceFormat(Number, long) for a target locale.
static String paceFormat(Locale locale, Number value, long interval, String one, String many, String none)
static byte[] parseBase64(String base64str)
Converts the string argument into an array of bytes.
static Date parseISODate(String dateStr)
Converts the string argumento into a Date value.
static Date parseISODateTime(String dateStr)
Converts the string argumento into a Date value.
static Date parseISOTime(String timeStr)
Converts the string argumento into a Date value.
static Date parseSmartDate(String dateStr, String... fmts)

Same as #parseSmartDateWithSeparator(String, String, String...) but with "[\\D-_\\s]+" as the default separator.

static Date parseSmartDateWithSeparator(String dateStr, String separator, String... fmts)

Tries to parse a date string applying an array of non lenient format patterns.

static String pluralize(Locale locale, String one, String many, Number n, Object... exts)

Same as #pluralize(String, String, Number, Object...) for the target locale.

static String pluralize(Locale locale, String one, String many, String none, Number n, Object... exts)

Same as #pluralize(String, String, String, Number, Object...) for the target locale.

static String pluralize(String one, String many, String none, Number n, Object... exts)

Applies the proper format for a given plural state.

static String pluralize(String one, String many, Number n, Object... exts)

Applies the proper format for a given plural state.

static MessageFormat pluralizeFormat(String template, Locale locale)

Same as pluralizeFormat(String) for the specified locale.

static MessageFormat pluralizeFormat(String pattern, String... choices)

Constructs a message with pluralization logic by the means of ChoiceFormat.

static MessageFormat pluralizeFormat(String template)

Constructs a message with pluralization logic from the given template.

static PrettyTimeFormat prettyTimeFormat()

Returns a thread-safe PrettyTimeFormat instance.

static PrettyTimeFormat prettyTimeFormat(Locale locale)

Same as prettyTimeFormat() for the specified locale.

static String replaceSupplementary(String value)

Replaces characters outside the Basic Multilingual Plane with their name.

static Number roundToSignificantFigures(Number num, int precision)

Rounds a number to significant figures.

static String simplify(String text)

Sort of poor man's transliteration, i.e.

static String slugify(String text)

Transforms a text into a representation suitable to be used in an URL.

static String spellBigNumber(Number value)

Converts a big number to a friendly text representation.

static String spellBigNumber(Number value, Locale locale)

Same as spellBigNumber(Number) for the specified locale.

static String spellDigit(Number value, Locale locale)

Same as spellDigit(Number) for the specified locale.

static String spellDigit(Number value)

For decimal digits [0-9], returns the number spelled out.

static String times(Number num, Locale locale)
Same as times(Number) for the specified locale.
static String times(Number num)
Interprets numbers as occurrences.
static String titleize(String text)

Converts the given text to title case smartly.

static String titleize(String text, String[] intCaps)

Converts the given text to title case smartly.

static String underscore(String text)

Makes a phrase underscored instead of spaced.

static String unmask(String mask, String value)

Parses the given text with the mask specified.

static String wordWrap(String value, int len)

Truncate a string to the closest word boundary after a number of characters.

[Expand]
Inherited Methods
From class java.lang.Object

Public Methods

public static String binaryPrefix (Number value)

Converts a given number to a string preceded by the corresponding binary International System of Units (SI) prefix.

Input Output
2 "2 bytes"
1536 "1.5 kB"
5242880 "5.00 MB"
1325899906842624L "1.18 PB"

Parameters
value Number to be converted
Returns
  • The number preceded by the corresponding binary SI prefix

public static String binaryPrefix (Number value, Locale locale)

Same as binaryPrefix(Number) for the specified locale.

Parameters
value Number to be converted
locale Target locale
Returns
  • The number preceded by the corresponding binary SI prefix

public static String camelize (String text, Locale locale)

Same as camelize(String) for the specified locale.

Parameters
text String to be camelized
locale Target locale
Returns
  • Camelized string

public static String camelize (String text, boolean capitalizeFirstChar)

Makes a phrase camel case. Spaces, hyphens, underscores and dots will be removed.

Parameters
text String to be camelized
capitalizeFirstChar true makes the first letter uppercase
Returns
  • Camelized string

public static String camelize (String text)

Same as camelize(String, boolean) with capitalize to false.

Parameters
text String to be camelized
Returns
  • Camelized string

public static String camelize (String text, boolean capitalizeFirstChar, Locale locale)

Same as camelize(String, boolean) for the specified locale.

Parameters
text String to be camelized
capitalizeFirstChar true makes the first letter uppercase
Returns
  • Camelized string

public static String capitalize (String text, Locale locale)

Same as capitalize(String) for the specified locale.

Parameters
text String to be capitalized
locale Target locale
Returns
  • capitalized string

public static String capitalize (String text)

Capitalizes the given text smartly.

Parameters
text String to be capitalized
Returns
  • capitalized string

public static DateFormat dateFormat (String pattern)

Returns a SimpleDateFormat instance for the current thread.

Date and Time Patterns

Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.

The following pattern letters are defined (all other characters from 'A' to 'Z' and from 'a' to 'z' are reserved):

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
Pattern letters are usually repeated, as their number determines the exact presentation:
  • Text: For formatting, if the number of pattern letters is 4 or more, the full form is used; otherwise a short or abbreviated form is used if available. For parsing, both forms are accepted, independent of the number of pattern letters.
  • Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.
  • Year: If the formatter's #getCalendar() Calendar is the Gregorian calendar, the following rules are applied.
    • For formatting, if the number of pattern letters is 2, the year is truncated to 2 digits; otherwise it is interpreted as a number.
    • For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D.
    • For parsing with the abbreviated year pattern ("y" or "yy"), SimpleDateFormat must interpret the abbreviated year relative to some century. It does this by adjusting dates to be within 80 years before and 20 years after the time the SimpleDateFormat instance is created. For example, using a pattern of "MM/dd/yy" and a SimpleDateFormat instance created on Jan 1, 1997, the string "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64" would be interpreted as May 4, 1964. During parsing, only strings consisting of exactly two digits, as defined by isDigit(char), will be parsed into the default century. Any other numeric string, such as a one digit string, a three or more digit string, or a two digit string that isn't all digits (for example, "-1"), is interpreted literally. So "01/02/3" or "01/02/003" are parsed, using the same pattern, as Jan 2, 3 AD. Likewise, "01/02/-3" is parsed as Jan 2, 4 BC.
    Otherwise, calendar system specific forms are applied. For both formatting and parsing, if the number of pattern letters is 4 or more, a calendar specific long form is used. Otherwise, a calendar specific short or abbreviated form is used.
  • Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.
  • General time zone: Time zones are interpreted as text if they have names. For time zones representing a GMT offset value, the following syntax is used:
         GMTOffsetTimeZone:
                 GMT Sign Hours : Minutes
         Sign: one of
                 + -
         Hours:
                 Digit
                 Digit Digit
         Minutes:
                 Digit Digit
         Digit: one of
                 0 1 2 3 4 5 6 7 8 9
     
    Hours must be between 0 and 23, and Minutes must be between 00 and 59. The format is locale independent and digits must be taken from the Basic Latin block of the Unicode standard.

    For parsing, RFC 822 time zones are also accepted.

  • RFC 822 time zone: For formatting, the RFC 822 4-digit time zone format is used:
         RFC822TimeZone:
                 Sign TwoDigitHours Minutes
         TwoDigitHours:
                 Digit Digit
     
    TwoDigitHours must be between 00 and 23. Other definitions are as for general time zones.

    For parsing, general time zones are also accepted.

SimpleDateFormat also supports localized date and time pattern strings. In these strings, the pattern letters described above may be replaced with other, locale dependent, pattern letters. SimpleDateFormat does not deal with the localization of text other than the pattern letters; that's up to the client of the class.

Examples

The following examples show how date and time patterns are interpreted in the U.S. locale. The given date and time are 2001-07-04 12:08:56 local time in the U.S. Pacific Time time zone.
Date and Time Pattern Result
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700

Parameters
pattern Format pattern that follows the conventions of java.text.SimpleDateFormat SimpleDateFormat
Returns
  • a DateFormat instance for the current thread

public static DateFormat dateFormat (String pattern, Locale locale)

Same as dateFormat(String) for the specified locale.

Parameters
pattern Format pattern that follows the conventions of java.text.SimpleDateFormat SimpleDateFormat
locale Target locale
Returns
  • a DateFormat instance for the current thread

public static String decamelize (String words, String replacement)

Converts a camel case string into a human-readable name.

Example assuming SPACE as replacement:

Input Output
"MyClass" "My Class"
"GL11Version" "GL 11 Version"
"AString" "A String"
"SimpleXMLParser" "Simple XML Parser"

Parameters
words String to be converted
replacement String to be interpolated
Returns
  • words converted to human-readable name

public static String decamelize (String words)

Same as decamelize(String) defaulting to SPACE for replacement

Parameters
words String to be converted
Returns
  • words converted to human-readable name

public static DecimalFormat decimalFormat (String pattern)

Returns a DecimalFormat instance for the current thread.

Parameters
pattern Format pattern that follows the conventions of DecimalFormat
Returns
  • a DecimalFormat instance for the current thread

public static DecimalFormat decimalFormat (String pattern, Locale locale)

Same as decimalFormat(String) for the specified locale.

Parameters
pattern Format pattern that follows the conventions of DecimalFormat
locale Target locale
Returns
  • a DecimalFormat instance for the current thread

public static String duration (Number seconds, Constants.TimeStyle style)

Formats a number of seconds as hours, minutes and seconds.

Parameters
seconds Number of seconds
style Time style
Returns
  • a String with the formatted time according to the given style

public static String duration (Number seconds, Constants.TimeStyle style, Locale locale)

Same as duration(Number, TimeStyle) for the specified locale.

Parameters
seconds Number of seconds
style Time style
locale Target locale
Returns
  • a String with the formatted time

public static String duration (Number seconds, Locale locale)

Same as duration(Number) for the specified locale.

Parameters
seconds Number of seconds
locale Target locale
Returns
  • a String with the formatted time

public static String duration (Number seconds)

Formats a number of seconds as hours, minutes and seconds. Defaults to STANDARD time style.

Parameters
seconds Number of seconds
Returns
  • a String with the formatted time

public static String fixLength (String text, int charsNum, char paddingChar, boolean left)

Pads or truncates a string to a specified length.

Parameters
text String to be fixed
charsNum The fixed length in number of chars
paddingChar The padding character
left true for left padding
Returns
  • A fixed length string

public static String fixLength (String text, int charsNum, char paddingChar)

Pads or truncates a string to a specified length.

Parameters
text String to be fixed
charsNum The fixed length in number of chars
paddingChar The padding character
Returns
  • A fixed length string

public static String format (Locale locale, String pattern, Object... args)

Same as #format(String, Object...) for the specified locale.

Parameters
locale The target locale
pattern Format pattern that follows the conventions of MessageFormat
args Arguments
Returns
  • The formatted String

public static String format (String pattern, Object... args)

Gets an ExtendedMessageFormat instance for the current thread with the given pattern and uses it to format a message with the specified arguments.

Parameters
pattern Format pattern that follows the conventions of MessageFormat
args Arguments
Returns
  • The formatted String

public static String formatCurrency (Number value, Locale locale)

Same as formatCurrency(Number) for the specified locale.

Parameters
value Number to be formatted
locale Target locale
Returns
  • String representing the monetary amount

public static String formatCurrency (Number value)

Smartly formats the given number as a monetary amount.

For en_GB:

Input Output
34 "£34"
1000 "£1,000"
12.5 "£12.50"

Parameters
value Number to be formatted
Returns
  • String representing the monetary amount

public static String formatDate (Date value, String pattern)

Formats a date according to the given pattern.

Parameters
value Date to be formatted
pattern The pattern.
Returns
  • a formatted date/time string

public static String formatDate (Date value, Locale locale)

Same as formatDate(Date) for the specified locale.

Parameters
value Date to be formatted
locale Target locale
Returns
  • String representation of the date

public static String formatDate (Date value)

Same as formatDate(int, Date) with SHORT style.

Parameters
value Date to be formatted
Returns
  • String representation of the date

public static String formatDate (int style, Date value)

Formats the given date with the specified style.

Parameters
style DateFormat style
value Date to be formatted
Returns
  • String representation of the date

public static String formatDate (Date value, String pattern, Locale locale)

Same as formatDate(Date, String) for the specified locale.

Parameters
value Date to be formatted
pattern The pattern.
locale Target locale
Returns
  • a formatted date/time string

public static String formatDate (int style, Date value, Locale locale)

Same as formatDate(int, Date) for the specified locale.

Parameters
style DateFormat style
value Date to be formatted
locale Target locale
Returns
  • String representation of the date

public static String formatDateTime (int dateStyle, int timeStyle, Date value)

Formats the given date/time with the specified styles.

Parameters
dateStyle Date style
timeStyle Time style
value Date to be formatted
Returns
  • String representation of the date

public static String formatDateTime (int dateStyle, int timeStyle, Date value, Locale locale)

Same as formatDateTime(int, int, Date) for the specified locale.

Parameters
dateStyle Date style
timeStyle Time style
value Date to be formatted
locale Target locale
Returns
  • String representation of the date

public static String formatDateTime (Date value, Locale locale)

Same as formatDateTime(Date) for the specified locale.

Parameters
value Date to be formatted
locale Target locale
Returns
  • String representation of the date

public static String formatDateTime (Date value)

Formats the given date/time with SHORT style.

Parameters
value Date to be formatted
Returns
  • String representation of the date

public static String formatDecimal (Number value)

Formats the given number to the standard decimal format for the default locale.

Parameters
value Number to be formatted
Returns
  • Standard localized format representation

public static String formatDecimal (Number value, Locale locale)

Same as formatDecimal(Number) for the specified locale.

Parameters
value Number to be formatted
locale Target locale
Returns
  • Standard localized format representation

public static String formatPercent (Number value, Locale locale)

Same as formatPercent(Number) for the specified locale.

Parameters
value Ratio to be converted
locale Target locale
Returns
  • String representing the percentage

public static String formatPercent (Number value)

Formats the given ratio as a percentage.

Input Output
0.5 "50%"
1 "100%"
0.564 "56%"

Parameters
value Ratio to be converted
Returns
  • String representing the percentage

public static boolean lossyEquals (Locale locale, String source, String target)

Same as lossyEquals(String, String) for the specified locale.

Parameters
locale The target locale
source The source string to be compared
target The target string to be compared
Returns
  • true if the two strings are equals according to primary differences only, false otherwise

public static boolean lossyEquals (String source, String target)

Locale-sensitive string comparison for primary differences.

 
 loosyEquals("Aáà-aa", "aaaaa") // == true 
 loosyEquals("abc", "cba") // == false
 
 

Parameters
source The source string to be compared
target The target string to be compared
Returns
  • true if the two strings are equals according to primary differences only, false otherwise

public static String mask (String mask, String value)

Formats the given text with the mask specified.

Parameters
mask The pattern mask.
value The text to be masked
Returns
  • The formatted text
See Also

public static MaskFormat maskFormat (String mask)

Returns a MaskFormat instance for the current thread.

Parameters
mask The pattern mask
Returns

public static MessageFormat messageFormat (String pattern, Locale locale)

Same as messageFormat(String) for the specified locale.

Parameters
pattern Format pattern that follows the conventions of java.text.MessageFormat MessageFormat
locale Target locale
Returns
  • a MessageFormat instance for the current thread

public static MessageFormat messageFormat (String pattern)

Returns a MessageFormat instance for the current thread.

Parameters
pattern Format pattern that follows the conventions of java.text.MessageFormat MessageFormat
Returns
  • a MessageFormat instance for the current thread

public static String metricPrefix (Number value)

Converts a given number to a string preceded by the corresponding decimal multiplicative prefix.

Input Output
200 "200"
1000 "1k"
3500000 "3.5M"

Parameters
value Number to be converted
Returns
  • The number preceded by the corresponding SI prefix

public static String metricPrefix (Number value, Locale locale)

Same as metricPrefix(Number) for the specified locale.

Parameters
value Number to be converted
locale Target locale
Returns
  • The number preceded by the corresponding SI prefix

public static String nanoTime (Number value)

Formats a number of nanoseconds as the proper ten power unit.

Parameters
value Number of nanoseconds
Returns
  • The transformed quantity preceded by the corresponding SI symbol

public static String nanoTime (Number value, Locale locale)

Same as nanoTime(Number) for the specified locale.

Parameters
value Number of nanoseconds
locale Target locale
Returns
  • The number preceded by the corresponding SI symbol

public static String naturalDay (int style, Date then, Locale locale)

Same as naturalDay(int, Date) with the given locale.

Parameters
style The style of the Date
then The date (GMT)
locale Target locale
Returns
  • String with 'today', 'tomorrow' or 'yesterday' compared to current day. Otherwise, returns a string formatted according to a locale sensitive DateFormat.

public static String naturalDay (Date then, Locale locale)

Same as naturalDay(Date) with the given locale.

Parameters
then The date
locale Target locale
Returns
  • String with 'today', 'tomorrow' or 'yesterday' compared to current day. Otherwise, returns a string formatted according to a locale sensitive DateFormat.

public static String naturalDay (int style, Date then)

For dates that are the current day or within one day, return 'today', 'tomorrow' or 'yesterday', as appropriate. Otherwise, returns a string formatted according to a locale sensitive DateFormat.

Parameters
style The style of the Date
then The date (GMT)
Returns
  • String with 'today', 'tomorrow' or 'yesterday' compared to current day. Otherwise, returns a string formatted according to a locale sensitive DateFormat.

public static String naturalDay (Date then)

Same as naturalDay(int, Date) with DateFormat.SHORT style.

Parameters
then The date
Returns
  • String with 'today', 'tomorrow' or 'yesterday' compared to current day. Otherwise, returns a string formatted according to a locale sensitive DateFormat.

public static String naturalTime (Date duration, TimeMillis precision, Locale locale)

Parameters
duration The duration
precision The precesion to retain in milliseconds
locale The locale
Returns
  • String representing the relative date

public static String naturalTime (Date reference, Date duration, Locale locale)

Same as naturalTime(Date, Date) for the specified locale.

Parameters
reference The reference
duration The duration
locale The locale
Returns
  • String representing the relative date

public static String naturalTime (Date reference, Date duration, long precision)

Computes both past and future relative dates with arbitrary precision.

Parameters
duration The duration
precision The precision to retain in milliseconds
Returns
  • String representing the relative date

public static String naturalTime (Date reference, Date duration, TimeMillis precision, Locale locale)

Parameters
reference The reference
duration The duration
precision The precesion to retain in milliseconds
locale The locale
Returns
  • String representing the relative date

public static String naturalTime (Date duration)

Same as naturalTime(Date, Date) with current date as reference.

Parameters
duration The duration
Returns
  • String representing the relative date

public static String naturalTime (Date duration, long precision, Locale locale)

Same as naturalTime(Date, long) for the specified locale.

Parameters
duration The duration
precision The precesion to retain in milliseconds
locale The locale
Returns
  • String representing the relative date

public static String naturalTime (Date duration, TimeMillis precision)

Parameters
duration The duration
precision The precision to retain in milliseconds
Returns
  • String representing the relative date

public static String naturalTime (Date reference, Date duration)

Computes both past and future relative dates.

E.g. 'one day ago', 'one day from now', '10 years ago', '3 minutes from now', 'right now' and so on.

Parameters
reference The reference
duration The duration
Returns
  • String representing the relative date

public static String naturalTime (Date duration, long precision)

Same as naturalTime(Date, Date, long) with current date as reference.

Parameters
duration The duration
precision The precision to retain in milliseconds
Returns
  • String representing the relative date

public static String naturalTime (Date duration, Locale locale)

Same as naturalTime(Date) for the specified locale.

Parameters
duration The duration
locale The locale
Returns
  • String representing the relative date

public static String naturalTime (Date reference, Date duration, long precision, Locale locale)

Same as naturalTime(Date, Date, long) for the specified locale.

Parameters
reference The reference
duration The duration
precision The precesion to retain in milliseconds
locale The locale
Returns
  • String representing the relative date

public static String naturalTime (Date reference, Date duration, TimeMillis precision)

Parameters
duration The duration
precision The precision to retain in milliseconds
Returns
  • String representing the relative date

public static String ordinal (Number value)

Converts a number to its ordinal as a string.

E.g. 1 becomes '1st', 2 becomes '2nd', 3 becomes '3rd', etc.

Parameters
value The number to convert
Returns
  • String representing the number as ordinal

public static String ordinal (Number value, Locale locale)

Same as ordinal(Number) for the specified locale.

Parameters
value The number to convert
locale The locale
Returns
  • String representing the number as ordinal

public static String oxford (Object[] items, int limit, String limitStr, Locale locale)

Same as oxford(Object[], int, String) for the specified locale.

Parameters
items The items array
limit The number of items to print. -1 for unbounded.
limitStr The string to be appended after extra items. Null or "" for default.
locale Target locale
Returns
  • human readable representation of a bounded list of items

public static String oxford (Object[] items)

Converts a list of items to a human readable string.

Parameters
items The items array
Returns
  • human readable representation of a bounded list of items

public static String oxford (Collection<?> items, int limit, String limitStr)

Converts a list of items to a human readable string with an optional limit.

Parameters
items The items collection
limit The number of items to print. -1 for unbounded.
limitStr The string to be appended after extra items. Null or "" for default.
Returns
  • human readable representation of a bounded list of items

public static String oxford (Collection<?> items, Locale locale)

Same as oxford(Object[]) for the specified locale.

Parameters
items The items collection
locale Target locale
Returns
  • human readable representation of a bounded list of items

public static String oxford (Object[] items, Locale locale)

Same as oxford(Object[]) for the specified locale.

Parameters
items The items array
locale Target locale
Returns
  • human readable representation of a bounded list of items

public static String oxford (Collection<?> items)

Converts a list of items to a human readable string.

Parameters
items The items collection
Returns
  • human readable representation of a bounded list of items

public static String oxford (Object[] items, int limit, String limitStr)

Converts a list of items to a human readable string with an optional limit.

Parameters
items The items array
limit The number of items to print. -1 for unbounded.
limitStr The string to be appended after extra items. Null or "" for default.
Returns
  • human readable representation of a bounded list of items

public static Pace pace (Number value, long interval)

Matches a pace (value and interval) with a logical time frame. Very useful for slow paces.

Examples:

 
   // 3 occurrences within a 3000ms interval
   pace(3, 3000); // => ~1/sec.
   
   // 200 occurrences within a 70000ms interval
   pace(200, 70000); // => ~3/sec.
   
   // 10 occurrences within a 70000ms interval
   pace(10, 70000); // => ~9/min.
   
   // 14 occurrences within a 31557600000ms interval (a year)
   pace(14, 31557600000L); // => ~1/month
   
   // 25 occurrences within a 31557600000ms interval
   pace(25, 31557600000L); // => ~2/month
   
   // 9 occurrences within a 31557600000ms interval
   pace(9, 31557600000L); // => >1/month (less than one per month)
 
 

Parameters
value The number of occurrences within the specified interval
interval The interval in milliseconds
Returns
  • a Pace instance with data for a given value and interval

public static String paceFormat (Number value, long interval, String one, String many, String none)

Matches a pace (value and interval) with a logical time frame. Very useful for slow paces.

Parameters
value The number of occurrences within the specified interval
interval The interval in milliseconds
one The message format for one time occurrences
many The message format for multiple times occurrences
none The message format for no occurrence
Returns
  • an human readable textual representation of the pace

public static String paceFormat (Number value, long interval)

Matches a pace (value and interval) with a logical time frame. Very useful for slow paces. e.g. heartbeats, ingested calories, hyperglycemic crises.

Parameters
value The number of occurrences within the specified interval
interval The interval in milliseconds
Returns
  • an human readable textual representation of the pace

public static String paceFormat (Locale locale, Number value, long interval)

Same as paceFormat(Number, long) for a target locale.

Parameters
locale The target locale
value The number of occurrences within the specified interval
interval The interval in milliseconds
Returns
  • an human readable textual representation of the pace

public static String paceFormat (Locale locale, Number value, long interval, String one, String many, String none)

Parameters
locale The target locale
value The number of occurrences within the specified interval
interval The interval in milliseconds
one The message format for one time occurrences
many The message format for multiple times occurrences
none The message format for no occurrence
Returns
  • an human readable textual representation of the pace

public static byte[] parseBase64 (String base64str)

Converts the string argument into an array of bytes.

Parameters
base64str The Base64 encoded string
Returns
  • an array of bytes with the decoded content

public static Date parseISODate (String dateStr)

Converts the string argumento into a Date value.

Parameters
dateStr The ISO8601 date string
Returns
  • the converted Date

public static Date parseISODateTime (String dateStr)

Converts the string argumento into a Date value.

Parameters
dateStr The ISO8601 date string
Returns
  • the converted Date

public static Date parseISOTime (String timeStr)

Converts the string argumento into a Date value.

Parameters
timeStr The ISO8601 time string
Returns
  • the converted Date

public static Date parseSmartDate (String dateStr, String... fmts)

Same as #parseSmartDateWithSeparator(String, String, String...) but with "[\\D-_\\s]+" as the default separator.

Example:
 Date target = newDate(2012, 1, 1, 0, 0, 0);
 
 String dates[] = new String[] { "1.2.12", "01.02.2012", "2012.02.01", "01-02-12", "1 2 2012" };
 
 for (String ds : dates)
 {
     Date date = Humanize.parseSmartDate(ds, "dd/MM/yy", "yyyy/MM/dd", "dd/MM/yyyy");
     Assert.assertEquals(date, target);
 }
 

Parameters
dateStr The date string
fmts An array of formats
Returns
  • the converted Date

public static Date parseSmartDateWithSeparator (String dateStr, String separator, String... fmts)

Tries to parse a date string applying an array of non lenient format patterns. The formats are automatically cached.

Parameters
dateStr The date string
separator The separator regexp
fmts An array of formats
Returns
  • the converted Date
See Also
  • #parseSmartDate(String, String...)

public static String pluralize (Locale locale, String one, String many, Number n, Object... exts)

Same as #pluralize(String, String, Number, Object...) for the target locale.

Parameters
locale Target locale
one Format for single element
many Format for many elements
n The number that triggers the plural state
exts Extended parameters for the specified formats
Returns
  • formatted text according the right plural state

public static String pluralize (Locale locale, String one, String many, String none, Number n, Object... exts)

Same as #pluralize(String, String, String, Number, Object...) for the target locale.

Parameters
locale Target locale
one Format for single element
many Format for many elements
none Format for no element
n The number that triggers the plural state
exts Extended parameters for the specified formats
Returns
  • formatted text according the right plural state

public static String pluralize (String one, String many, String none, Number n, Object... exts)

Applies the proper format for a given plural state.

Example:
 pluralize("There is one file on {1}.", "There are {0} files on {1}.", "There are no files on {1}.", 1, "disk");
 // == There is one file on disk.
 pluralize("There is one file on {1}.", "There are {0} files on {1}.", "There are no files on {1}.", 2, "disk");
 // == There are 2 files on disk.
 pluralize("There is one file on {1}.", "There are {0} files on {1}.", "There are no files on {1}.", 0, "disk");
 // == There are no files on disk.
 
 pluralize("one", "{0}", "none", 1);
 // = "one"
 pluralize("one", "{0}", "none", 2);
 // = "2"
 

Parameters
one Format for single element
many Format for many elements
none Format for no element
n The number that triggers the plural state
exts Extended parameters for the specified formats
Returns
  • formatted text according the right plural state

public static String pluralize (String one, String many, Number n, Object... exts)

Applies the proper format for a given plural state.

Example:
 pluralize("There is one file on {1}.", "There are {0} files on {1}.", 1, "disk");
 // == There is one file on disk.
 pluralize("There is one file on {1}.", "There are {0} files on {1}.", 2, "disk");
 // == There are 2 files on disk.
 

Parameters
one Format for single element
many Format for many elements
n The number that triggers the plural state
exts Extended parameters for the specified formats
Returns
  • formatted text according the right plural state

public static MessageFormat pluralizeFormat (String template, Locale locale)

Same as pluralizeFormat(String) for the specified locale.

Parameters
template String of tokens delimited by '::'
locale Target locale
Returns
  • Message instance prepared to generate pluralized strings

public static MessageFormat pluralizeFormat (String pattern, String... choices)

Constructs a message with pluralization logic by the means of ChoiceFormat.

Parameters
pattern Base pattern
choices Values that match the pattern
Returns
  • Message instance prepared to generate pluralized strings

public static MessageFormat pluralizeFormat (String template)

Constructs a message with pluralization logic from the given template.

Examples:
 MessageFormat msg = pluralize("There {0} on {1}.::are no files::is one file::are {2} files");
 
 msg.render(0, "disk"); // == "There are no files on disk."
 msg.render(1, "disk"); // == "There is one file on disk."
 msg.render(1000, "disk"); // == "There are 1,000 files on disk."
 
 MessageFormat msg = pluralize("nothing::one thing::{0} things");
 
 msg.render(-1); // == "nothing"
 msg.render(0); // == "nothing"
 msg.render(1); // == "one thing"
 msg.render(2); // == "2 things"
 
 MessageFormat msg = pluralize("one thing::{0} things");
 
 msg.render(-1); // == "-1 things"
 msg.render(0); // == "0 things"
 msg.render(1); // == "one thing"
 msg.render(2); // == "2 things"
 

Parameters
template String of tokens delimited by '::'
Returns
  • Message instance prepared to generate pluralized strings

public static PrettyTimeFormat prettyTimeFormat ()

Returns a thread-safe PrettyTimeFormat instance.

Returns
  • PrettyTimeFormat instance
See Also

public static PrettyTimeFormat prettyTimeFormat (Locale locale)

Same as prettyTimeFormat() for the specified locale.

Parameters
locale Target locale
Returns
  • PrettyTimeFormat instance
See Also

public static String replaceSupplementary (String value)

Replaces characters outside the Basic Multilingual Plane with their name.

Parameters
value The text to be matched
Returns
  • text with characters outside BMP replaced by their unicode numbers or the given text unaltered

public static Number roundToSignificantFigures (Number num, int precision)

Rounds a number to significant figures.

Parameters
num The number to be rounded
precision The number of significant digits
Returns
  • The number rounded to significant figures

public static String simplify (String text)

Sort of poor man's transliteration, i.e. normalizes and strips diacritical marks.

Input Output
"J'étudie le français" "J'etudie le francais"
"Lo siento, no hablo español." "Lo siento, no hablo espanol."

Parameters
text The text to be simplified.
Returns
  • simplified text.

public static String slugify (String text)

Transforms a text into a representation suitable to be used in an URL.

Input Output
"J'étudie le français" "jetudie-le-francais"
"Lo siento, no hablo español." "lo-siento-no-hablo-espanol"

Parameters
text The text to be slugified
Returns
  • Slugified String

public static String spellBigNumber (Number value)

Converts a big number to a friendly text representation. Accepts values ranging from thousands to googols. Uses BigDecimal.

Parameters
value Number to be converted
Returns
  • Friendly text representation of the given value

public static String spellBigNumber (Number value, Locale locale)

Same as spellBigNumber(Number) for the specified locale.

Parameters
value Number to be converted
locale Target locale
Returns
  • Friendly text representation of the given value

public static String spellDigit (Number value, Locale locale)

Same as spellDigit(Number) for the specified locale.

Parameters
value Decimal digit
locale Target locale
Returns
  • String representing the number spelled out

public static String spellDigit (Number value)

For decimal digits [0-9], returns the number spelled out. Otherwise, returns the number as string.

Input Output
1 "one"
2 "two"
10 "10"

Parameters
value Decimal digit
Returns
  • String representing the number spelled out

public static String times (Number num, Locale locale)

Same as times(Number) for the specified locale.

Parameters
num The number of occurrences
locale Target locale
Returns
  • textual representation of the number as occurrences

public static String times (Number num)

Interprets numbers as occurrences.

Parameters
num The number of occurrences
Returns
  • textual representation of the number as occurrences

public static String titleize (String text)

Converts the given text to title case smartly.

Known limitations:
  • Phrasal verb detection
Applies Quick Guide to Capitalization in English at SAP.

Capitalize

  • Nouns
  • Verbs (including is and other forms of be)
  • Participles
  • Adverbs (including than and when)
  • Adjectives (including this, that, and each)
  • Pronouns (including its)
  • Subordinating conjunctions (if, because, as, that)
  • Prepositions and conjunctions with five or more letters (between, without, during, about, because, through)
  • First and last words, no matter what part of speech they are
  • Prepositions that are part of a verb phrase (Logging On, Setting Up)
  • Both elements of hyphenated words (How-To, Country-Specific)
  • Words and phrases in parentheses as you would capitalize them if they did not appear in parentheses
  • Any words, phrases, fragments, or sentences after a colon or semicolon

Do Not Capitalize

  • Coordinating conjunctions (and, but, or, nor, for)
  • Prepositions of four or fewer letters (with, to, for, at, and so on)
  • Articles (a, an, the, some) unless the article is the first or last word in the title
  • The word to in an infinitive phrase
  • Case-specific product names, words, or phrases (mySAP.com, README file, e-Business, and so on)

Parameters
text Text to be converted
Returns
  • a nice styled title

public static String titleize (String text, String[] intCaps)

Converts the given text to title case smartly.

Parameters
text Text to be converted
intCaps An internal capitalized word list
Returns
  • a nice styled title

public static String underscore (String text)

Makes a phrase underscored instead of spaced.

Parameters
text Phrase to underscore
Returns
  • converted String

public static String unmask (String mask, String value)

Parses the given text with the mask specified.

Parameters
mask The pattern mask.
value The text to be parsed
Returns
  • The parsed text
Throws
ParseException
ParseException
See Also

public static String wordWrap (String value, int len)

Truncate a string to the closest word boundary after a number of characters.

Parameters
value Text to be truncated
len Number of characters
Returns
  • String truncated to the closes word boundary