Development Tip

Java에서 Duration을 어떻게 "예쁜 인쇄"할 수 있습니까?

yourdevel 2020. 10. 20. 08:13
반응형

Java에서 Duration을 어떻게 "예쁜 인쇄"할 수 있습니까?


C #과 같은 방식으로 밀리 초 단위로 숫자를 인쇄 할 수있는 Java 라이브러리를 아는 사람이 있습니까?

예를 들어 123456 ms는 4d1h3m5s로 인쇄됩니다.


Joda TimePeriodFormatterBuilder를 사용하여이를 수행하는 꽤 좋은 방법을 가지고 있습니다.

빠른 승리: PeriodFormat.getDefault().print(duration.toPeriod());

예 :

//import org.joda.time.format.PeriodFormatter;
//import org.joda.time.format.PeriodFormatterBuilder;
//import org.joda.time.Duration;

Duration duration = new Duration(123456); // in milliseconds
PeriodFormatter formatter = new PeriodFormatterBuilder()
     .appendDays()
     .appendSuffix("d")
     .appendHours()
     .appendSuffix("h")
     .appendMinutes()
     .appendSuffix("m")
     .appendSeconds()
     .appendSuffix("s")
     .toFormatter();
String formatted = formatter.print(duration.toPeriod());
System.out.println(formatted);

Java 8 Duration.toString()과 약간의 정규식을 사용하여 간단한 솔루션을 구축했습니다 .

public static String humanReadableFormat(Duration duration) {
    return duration.toString()
            .substring(2)
            .replaceAll("(\\d[HMS])(?!$)", "$1 ")
            .toLowerCase();
}

결과는 다음과 같습니다.

- 5h
- 7h 15m
- 6h 50m 15s
- 2h 5s
- 0.1s

사이에 공백을 사용하지 않으려면 replaceAll.


Apache commons-lang은이 작업을 수행하는 데 유용한 클래스를 제공합니다. DurationFormatUtils

DurationFormatUtils.formatDurationHMS( 15362 * 1000 ) )=> 4 : 16 : 02.000 (H : m : s.millis) DurationFormatUtils.formatDurationISO( 15362 * 1000 ) )=> P0Y0M0DT4H16M2.000S, cf. ISO8601


JodaTime는 갖는 Period이러한 양을 나타낼 수있는 클래스 및 (통해 렌더링 될 수 IsoPeriodFormat투입) ISO8601 예 형식 PT4D1H3M5S, 예를

Period period = new Period(millis);
String formatted = ISOPeriodFormat.standard().print(period);

해당 형식이 원하는 형식이 아닌 경우 PeriodFormatterBuilderC # 스타일을 포함하여 임의의 레이아웃을 조합 할 수 있습니다 4d1h3m5s.


Java 8 에서는 PT8H6M12.345S와 같은 ISO 8601 초 기반 표현을 사용하여 외부 라이브러리없이 포맷 하는 toString()방법을 사용할 수도 있습니다 .java.time.Duration


순수한 JDK 코드를 사용하여 수행하는 방법은 다음과 같습니다.

import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;

long diffTime = 215081000L;
Duration duration = DatatypeFactory.newInstance().newDuration(diffTime);

System.out.printf("%02d:%02d:%02d", duration.getDays() * 24 + duration.getHours(), duration.getMinutes(), duration.getSeconds()); 

이것이 귀하의 사용 사례에 정확히 맞지 않을 수도 있지만 PrettyTime 이 여기에서 유용 할 수 있습니다.

PrettyTime p = new PrettyTime();
System.out.println(p.format(new Date()));
//prints: “right now”

System.out.println(p.format(new Date(1000*60*10)));
//prints: “10 minutes from now”

자바 9 이상

Duration d1 = Duration.ofDays(0);
        d1 = d1.plusHours(47);
        d1 = d1.plusMinutes(124);
        d1 = d1.plusSeconds(124);
System.out.println(String.format("%s d %sh %sm %ss", 
                d1.toDaysPart(), 
                d1.toHoursPart(), 
                d1.toMinutesPart(), 
                d1.toSecondsPart()));

2 일 1 시간 6 분 4 초


org.threeten.extra.AmountFormats.wordBased

The ThreeTen-Extra project, which is maintained by Stephen Colebourne, the author of JSR 310, java.time, and Joda-Time, has an AmountFormats class which works with the standard Java 8 date time classes. It's fairly verbose though, with no option for more compact output.

Duration d = Duration.ofMinutes(1).plusSeconds(9).plusMillis(86);
System.out.println(AmountFormats.wordBased(d, Locale.getDefault()));

1 minute, 9 seconds and 86 milliseconds


An alternative to the builder-approach of Joda-Time would be a pattern-based solution. This is offered by my library Time4J. Example using the class Duration.Formatter (added some spaces for more readability - removing the spaces will yield the wished C#-style):

IsoUnit unit = ClockUnit.MILLIS;
Duration<IsoUnit> dur = Duration.of(123456, unit).with(Duration.STD_PERIOD);
String s = Duration.Formatter.ofPattern("D'd' h'h' m'm' s.fff's'").format(dur);
System.out.println(s); // output: 0d 0h 2m 3.456s

Another way is using the class net.time4j.PrettyTime (which is also good for localized output and printing relative times):

s = PrettyTime.of(Locale.ENGLISH).print(dur, TextWidth.NARROW);
System.out.println(s); // output: 2m 3s 456ms

A Java 8 version based on user678573's answer:

    private static String humanReadableFormat(Duration duration) {
    return String.format("%s days and %sh %sm %ss", duration.toDays(),
            duration.toHours() - TimeUnit.DAYS.toHours(duration.toDays()),
            duration.toMinutes() - TimeUnit.HOURS.toMinutes(duration.toHours()),
            duration.getSeconds() - TimeUnit.MINUTES.toSeconds(duration.toMinutes()));
}

... since there is no PeriodFormatter in Java 8 and no methods like getHours, getMinutes, ...

I'd be happy to see a better version for Java 8.

참고URL : https://stackoverflow.com/questions/3471397/how-can-i-pretty-print-a-duration-in-java

반응형