Localization of a time interval in Java

I need to represent the time interval as a localized string as follows: 10 hours 25 minutes 1 seconddepending on Locale. This is pretty easy to implement manually in English: String hourStr = hours == 1 ? "hour" : "hours"etc.

But I need some kind of "ready-made" Java (possibly Java8) mechanism in accordance with the rules of different languages. Does it have Java, or do I need to implement it for each Locale used in the application, independently?

+4
source share
1 answer

Joda-Time. , , , , , , , 2.5.

Period period = new Period(new LocalDate(2013, 4, 11), LocalDate.now());
PeriodFormatter formatter = PeriodFormat.wordBased(Locale.GERMANY);
System.out.println(formatter.print(period)); // output: 1 Jahr, 2 Monate und 3 Wochen

formatter = formatter.withLocale(Locale.ENGLISH);
System.out.println(formatter.print(period)); // output: 1 Jahr, 2 Monate und 3 Wochen (bug???)

formatter = PeriodFormat.wordBased(Locale.ENGLISH);
System.out.println(formatter.print(period)); // output: 1 year, 2 months and 3 weeks

, . -- , ( ):

PeriodFormat.space=\ 
PeriodFormat.comma=,
PeriodFormat.commandand=,and 
PeriodFormat.commaspaceand=, and 
PeriodFormat.commaspace=, 
PeriodFormat.spaceandspace=\ and 
PeriodFormat.year=\ year
PeriodFormat.years=\ years
PeriodFormat.month=\ month
PeriodFormat.months=\ months
PeriodFormat.week=\ week
PeriodFormat.weeks=\ weeks
PeriodFormat.day=\ day
PeriodFormat.days=\ days
PeriodFormat.hour=\ hour
PeriodFormat.hours=\ hours
PeriodFormat.minute=\ minute
PeriodFormat.minutes=\ minutes
PeriodFormat.second=\ second
PeriodFormat.seconds=\ seconds
PeriodFormat.millisecond=\ millisecond
PeriodFormat.milliseconds=\ milliseconds

2.5, , . , , ( ). , . .

: Java 8, , .

2015-08-26:

Time4J-v4.3 ( Maven Central) , 45 :

import static net.time4j.CalendarUnit.*;
import static net.time4j.ClockUnit.*;

// the input for creating the duration (in Joda-Time called Period)
IsoUnit[] units = {YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS};
PlainTimestamp start = PlainDate.of(2013, 4, 11).atTime(13, 45, 21);
PlainTimestamp end = SystemClock.inLocalView().now();

// create the duration
Duration<?> duration = Duration.in(units).between(start, end);

// print the duration (here not abbreviated, but with full unit names)
String s = PrettyTime.of(Locale.US).print(duration, TextWidth.WIDE);

System.out.println(s);
// example output: 1 year, 5 months, 7 days, 3 hours, 25 minutes, and 49 seconds

Time4J ?

  • , .
  • 45 .
  • , , , , .
  • ( , "" )
  • 3 : WIDE, ABBREVIATED (SHORT) NARROW
  • Java-8 , Java-8-, java.time.Period java.time.Duration, Time4J.
+2

Source: https://habr.com/ru/post/1546790/


All Articles