Package net.time4j

Class PrettyTime

java.lang.Object
net.time4j.PrettyTime

public final class PrettyTime extends Object

Enables formatted output as usually used in social media in different languages.

Parsing is not included because there is no general solution for all locales. Instead users must keep the backing duration object and use it for printing.

Since:
1.2
Author:
Meno Hochschild
  • Method Details

    • of

      public static PrettyTime of(Locale locale)

      Gets an instance of PrettyTime for given language, possibly cached.

      Parameters:
      locale - the language an instance is searched for
      Returns:
      pretty time object for formatting durations or relative time
      Since:
      1.2
    • getLocale

      public Locale getLocale()

      Gets the language of this instance.

      Returns:
      language
      Since:
      1.2
    • getReferenceClock

      public TimeSource<?> getReferenceClock()

      Yields the reference clock for formatting of relative times.

      Returns:
      reference clock or system clock if not yet specified
      Since:
      1.2
      See Also:
      withReferenceClock(TimeSource), printRelative(UnixTime, TZID), printRelative(UnixTime, String)
    • withReferenceClock

      public PrettyTime withReferenceClock(TimeSource<?> clock)

      Yields a changed copy of this instance with given reference clock.

      Parameters:
      clock - new reference clock
      Returns:
      new instance of PrettyTime with changed reference clock
      Since:
      1.2
      See Also:
      getReferenceClock(), printRelative(UnixTime, TZID), printRelative(UnixTime, String)
    • withNumerals

      public PrettyTime withNumerals(NumberSystem numsys)

      Defines the given number system for representing amounts.

      If decimal then the zero digit will also be adjusted appropriately.

      Parameters:
      numsys - number system
      Returns:
      changed copy of this instance
      Since:
      5.9
      See Also:
      withZeroDigit(char)
    • withZeroDigit

      @Deprecated public PrettyTime withZeroDigit(NumberSystem numberSystem)

      Defines the localized zero digit based on given decimal number system.

      Parameters:
      numberSystem - decimal number system
      Returns:
      changed copy of this instance
      Throws:
      IllegalArgumentException - if the number system is not decimal
      Since:
      3.24/4.20
      See Also:
      withZeroDigit(char)
    • withZeroDigit

      public PrettyTime withZeroDigit(char zeroDigit)

      Defines the localized zero digit.

      In most languages the zero digit is just ASCII-"0", but for example in arabic locales the digit can also be the char U+0660. By default Time4J will try to use the configuration of the module i18n or else the JDK-setting. This method can override it however.

      Note: This method can only produce sensible results if all digits 0-9 can be mapped to code points starting with given zero digit char.

      Parameters:
      zeroDigit - localized zero digit
      Returns:
      changed copy of this instance
      Since:
      1.2
      See Also:
      DecimalFormatSymbols.getZeroDigit(), NumberSymbolProvider.getZeroDigit(Locale)
    • withMinusSign

      public PrettyTime withMinusSign(String minusSign)

      Defines the localized minus sign.

      In most languages the minus sign is just U+002D. By default Time4J will try to use the configuration of the module i18n or else the JDK-setting. This method can override it however. Especially for arabic, it might make sense to first add a unicode marker (either LRM U+200E or RLM U+200F) in front of the minus sign in order to control the orientation in right-to-left-style.

      Parameters:
      minusSign - localized minus sign (possibly with unicode markers)
      Returns:
      changed copy of this instance
      Since:
      2.1
      See Also:
      DecimalFormatSymbols.getMinusSign(), NumberSymbolProvider.getMinusSign(Locale)
    • withEmptyUnit

      public PrettyTime withEmptyUnit(CalendarUnit emptyUnit)

      Defines the time unit used for formatting an empty duration.

      Time4J uses seconds as default. This method can override the default however.

      Parameters:
      emptyUnit - time unit for usage in an empty duration
      Returns:
      changed copy of this instance
      Since:
      1.2
      See Also:
      print(Duration, TextWidth)
    • withEmptyUnit

      public PrettyTime withEmptyUnit(ClockUnit emptyUnit)

      Defines the time unit used for formatting an empty duration.

      Time4J uses seconds as default. This method can override the default however.

      Parameters:
      emptyUnit - time unit for usage in an empty duration
      Returns:
      changed copy of this instance
      Since:
      1.2
      See Also:
      print(Duration, TextWidth)
    • withWeeksToDays

      public PrettyTime withWeeksToDays()

      Determines that weeks will always be normalized to days.

      Returns:
      changed copy of this instance
      Since:
      2.0
    • withShortStyle

      public PrettyTime withShortStyle()

      Mandates the use of abbreviations as default style.

      All print()-methods with explicit TextWidth-parameters will ignore this setting however. This method is mainly relevant for printing relative times.

      Returns:
      changed copy of this instance
      Since:
      3.6/4.4
    • withDefaultListSeparator

      public PrettyTime withDefaultListSeparator(String separator)

      Mandates the use of given default list separator.

      Usually the locale specifies any list patterns for printing durations. However, this method allows customized list separators. Example:

           assertThat(
            PrettyTime.of(Locale.US)
                .withDefaultListSeparator(" | ")
                .withLastListSeparator(" + ")
                .print(Duration.ofCalendarUnits(1, 2, 3), TextWidth.WIDE),
            is("1 year | 2 months + 3 days"));
       
      Parameters:
      separator - the separator characters between any duration items
      Returns:
      changed copy of this instance
      Since:
      5.2
      See Also:
      withLastListSeparator(String)
    • withLastListSeparator

      public PrettyTime withLastListSeparator(String separator)

      Mandates the use of given list separator at the last position.

      Important: A default list separator must be specified otherwise this method will have no effect.

      Parameters:
      separator - the separator characters between the last two duration items
      Returns:
      changed copy of this instance
      Since:
      5.2
      See Also:
      withDefaultListSeparator(String)
    • printYesterday

      public String printYesterday()

      Determines the localized word for "yesterday".

      Returns:
      String
      Since:
      3.43/4.38
    • printToday

      public String printToday()

      Determines the localized word for "today".

      Returns:
      String
      Since:
      3.24/4.20
    • printTomorrow

      public String printTomorrow()

      Determines the localized word for "tomorrow".

      Returns:
      String
      Since:
      3.43/4.38
    • printLast

      public String printLast(Weekday weekday)

      Obtains the localized word for given last day-of-week if available.

      Parameters:
      weekday - the last day of week
      Returns:
      localized word, maybe empty
      Since:
      5.1
    • printNext

      public String printNext(Weekday weekday)

      Obtains the localized word for given next day-of-week if available.

      Parameters:
      weekday - the next day of week
      Returns:
      localized word, maybe empty
      Since:
      5.1
    • print

      public String print(long amount, CalendarUnit unit, TextWidth width)

      Formats given duration in calendar units.

      Note: Millennia, centuries and decades are automatically normalized to years while quarter-years are normalized to months.

      Parameters:
      amount - count of units (quantity)
      unit - calendar unit
      width - text width (ABBREVIATED as synonym for SHORT)
      Returns:
      formatted output
      Since:
      1.2
      See Also:
      print(Duration, TextWidth)
    • print

      public String print(long amount, ClockUnit unit, TextWidth width)

      Formats given duration in clock units.

      Parameters:
      amount - count of units (quantity)
      unit - clock unit
      width - text width (ABBREVIATED as synonym for SHORT)
      Returns:
      formatted output
      Since:
      1.2
      See Also:
      print(Duration, TextWidth)
    • print

      public String print(Duration<?> duration)

      Formats the total given duration.

      A localized output is only supported for the units CalendarUnit.YEARS, CalendarUnit.MONTHS, CalendarUnit.WEEKS, CalendarUnit.DAYS and all ClockUnit-units. This method performs an internal normalization if any other unit is involved.

      Note: This method uses full words by default. If withShortStyle() is called then abbreviations will be used.

      Parameters:
      duration - object representing a duration which might contain several units and quantities
      Returns:
      formatted list output
      Since:
      3.6/4.4
    • print

      public String print(TemporalAmount threeten)

      Short-cut for print(Duration.from(threeten)).

      Parameters:
      threeten - object representing a duration which might contain several units and quantities
      Returns:
      formatted list output in normalized form
      Throws:
      IllegalArgumentException - in case of conversion failures
      Since:
      4.4
      See Also:
      print(Duration)
    • print

      public String print(Duration<?> duration, TextWidth width)

      Formats the total given duration.

      A localized output is only supported for the units CalendarUnit.YEARS, CalendarUnit.MONTHS, CalendarUnit.WEEKS, CalendarUnit.DAYS and all ClockUnit-units. This method performs an internal normalization if any other unit is involved.

      Parameters:
      duration - object representing a duration which might contain several units and quantities
      width - text width (ABBREVIATED as synonym for SHORT)
      Returns:
      formatted list output
      Since:
      1.2
    • print

      public String print(TemporalAmount threeten, TextWidth width)

      Short-cut for print(Duration.from(threeten), width).

      Parameters:
      threeten - object representing a duration which might contain several units and quantities
      width - text width (ABBREVIATED as synonym for SHORT)
      Returns:
      formatted list output in normalized form
      Throws:
      IllegalArgumentException - in case of conversion failures
      Since:
      4.0
      See Also:
      print(Duration, TextWidth)
    • print

      public String print(Duration<?> duration, TextWidth width, boolean printZero, int maxLength)

      Formats given duration.

      Like print(Duration, TextWidth), but offers the option to limit the count of displayed duration items and also to print items with zero amount. The first printed duration item has always a non-zero amount however. Example:

        Duration<?> dur =
            Duration.ofZero().plus(1, DAYS).plus(4, ClockUnit.MINUTES);
        System.out.println(
            PrettyTime.of(Locale.FRANCE).print(dur, TextWidth.WIDE, true, 3));
        // output: 1 jour, 0 heure et 4 minutes
       
      Parameters:
      duration - object representing a duration which might contain several units and quantities
      width - text width (ABBREVIATED as synonym for SHORT)
      printZero - determines if zero amounts shall be printed, too
      maxLength - maximum count of displayed items
      Returns:
      formatted list output
      Throws:
      IllegalArgumentException - if maxLength is smaller than 1
      Since:
      2.0
    • print

      public String print(TemporalAmount threeten, TextWidth width, boolean printZero, int maxLength)

      Short-cut for print(Duration.from(threeten), width, printZero, maxLength).

      Parameters:
      threeten - object representing a duration which might contain several units and quantities
      width - text width (ABBREVIATED as synonym for SHORT)
      printZero - determines if zero amounts shall be printed, too
      maxLength - maximum count of displayed items
      Returns:
      formatted list output in normalized form
      Throws:
      IllegalArgumentException - if maxLength is smaller than 1 or in case of conversion failures
      Since:
      4.0
      See Also:
      print(Duration, TextWidth, boolean, int)
    • printRelativeInStdTimezone

      public String printRelativeInStdTimezone(UnixTime moment)

      Formats given time point relative to the current time of getReferenceClock() as duration in at most second precision or less - using the system timezone.

      Parameters:
      moment - relative time point
      Returns:
      formatted output of relative time, either in past or in future
      Since:
      3.4/4.3
      See Also:
      printRelative(UnixTime, Timezone, TimeUnit)
    • printRelative

      public String printRelative(UnixTime moment, TZID tzid)

      Formats given time point relative to the current time of getReferenceClock() as duration in at most second precision or less.

      Example how to query for a coming leap second:

            TimeSource<?> clock = () -> PlainTimestamp.of(2015, 6, 30, 23, 59, 54).atUTC();
            String remainingDurationInRealSeconds =
                PrettyTime.of(Locale.ENGLISH).withReferenceClock(clock).printRelative(
                    PlainTimestamp.of(2015, 7, 1, 0, 0, 0).atUTC(),
                    ZonalOffset.UTC);
            System.out.println(remainingDurationInRealSeconds); // in 7 seconds
       
      Parameters:
      moment - relative time point
      tzid - time zone id for translating to a local duration
      Returns:
      formatted output of relative time, either in past or in future
      Since:
      1.2
      See Also:
      printRelative(UnixTime, Timezone, TimeUnit)
    • printRelative

      public String printRelative(UnixTime moment, String tzid)

      Formats given time point relative to the current time of getReferenceClock() as duration in at most second precision or less.

      Parameters:
      moment - relative time point
      tzid - time zone id for translating to a local duration
      Returns:
      formatted output of relative time, either in past or in future
      Since:
      1.2
      See Also:
      printRelative(UnixTime, Timezone, TimeUnit)
    • printRelative

      public String printRelative(ZonedDateTime zdt)

      Formats given threeten object relative to the current time of getReferenceClock() as duration in at most second precision or less.

      Parameters:
      zdt - relative time
      Returns:
      formatted output of relative time, either in past or in future
      Since:
      4.8
      See Also:
      printRelative(Instant, ZoneId)
    • printRelative

      public String printRelative(Instant instant, ZoneId zoneId)

      Formats given time point relative to the current time of getReferenceClock() as duration in at most second precision or less.

      Parameters:
      instant - relative time point
      zoneId - time zone id for translating to a local duration
      Returns:
      formatted output of relative time, either in past or in future
      Since:
      4.8
      See Also:
      printRelative(UnixTime, Timezone, TimeUnit)
    • printRelative

      public String printRelative(UnixTime moment, Timezone tz, TimeUnit precision)

      Formats given time point relative to the current time of getReferenceClock() as duration in given precision or less.

      If day precision is given then output like "today", "yesterday", "tomorrow" or "last Wednesday" is possible. Example:

            TimeSource<?> clock = () -> PlainTimestamp.of(2015, 8, 1, 10, 24, 5).atUTC();
            String durationInDays =
                PrettyTime.of(Locale.GERMAN).withReferenceClock(clock).printRelative(
                    PlainTimestamp.of(2015, 8, 1, 17, 0).atUTC(),
                    Timezone.of(EUROPE.BERLIN),
                    TimeUnit.DAYS);
            System.out.println(durationInDays); // heute (german word for today)
       
      Parameters:
      moment - relative time point
      tz - time zone for translating to a local duration
      precision - maximum precision of relative time (not more than seconds)
      Returns:
      formatted output of relative time, either in past or in future
      Since:
      3.6/4.4
    • printRelativeOrDateTime

      public String printRelativeOrDateTime(UnixTime moment, Timezone tz, TimeUnit precision, long maxdelta, TemporalFormatter<Moment> formatter)

      Formats given time point relative to the current time of getReferenceClock() as duration in given precision or as absolute date-time.

      If the calculated duration in seconds is bigger than maxdelta then the absolute date-time will be printed else a relative expression will be used.

      Parameters:
      moment - relative time point
      tz - time zone for translating to a local duration
      precision - maximum precision of relative time (not more than seconds)
      maxdelta - maximum deviation of given moment from clock in posix seconds for relative printing
      formatter - used for printing absolute time if the deviation is bigger than maxdelta
      Returns:
      formatted output of relative time, either in past or in future
      Since:
      3.6/4.4
    • printRelativeOrDateTime

      public String printRelativeOrDateTime(UnixTime moment, Timezone tz, TimeUnit precision, CalendarUnit maxRelativeUnit, TemporalFormatter<Moment> formatter)

      Formats given time point relative to the current time of getReferenceClock() as duration in given precision or as absolute date-time.

      Parameters:
      moment - time point whose deviation from clock is to be printed
      tz - time zone for translating to a local duration
      precision - maximum precision of relative time (not more than seconds)
      maxRelativeUnit - maximum time unit which will still be printed in a relative way
      formatter - used for printing absolute time if the leading unit is bigger than maxRelativeUnit
      Returns:
      formatted output of relative time, either in past or in future
      Since:
      3.6/4.4
    • printRelativeOrDate

      public String printRelativeOrDate(PlainDate date, TZID tzid, CalendarUnit maxRelativeUnit, TemporalFormatter<PlainDate> formatter)

      Formats given date relative to the current date of getReferenceClock() as duration or as absolute date.

      Parameters:
      date - calendar date whose deviation from clock is to be printed
      tzid - time zone identifier for getting current reference date
      maxRelativeUnit - maximum calendar unit which will still be printed in a relative way
      formatter - used for printing absolute date if the leading unit is bigger than maxRelativeUnit
      Returns:
      formatted output of relative date, either in past or in future
      Since:
      3.7/4.5