source

Java로 기간을 포맷하는 방법(예: H 형식:MM:SS)

goodcode 2022. 8. 29. 22:09
반응형

Java로 기간을 포맷하는 방법(예: H 형식:MM:SS)

H:와 같은 패턴을 사용하여 시간(초)을 포맷하고 싶습니다.MM:SS. Java의 현재 유틸리티는 시간은 포맷하지 않고 시간을 포맷하도록 설계되었습니다.

라이브러리로 끌지 않으려면 포메터 또는 관련 바로 가기(초 단위)를 사용하면 됩니다.

  String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));

Apache common의 Duration Format Utils를 다음과 같이 사용합니다.

DurationFormatUtils.formatDuration(millis, "**H:mm:ss**", true);

8 이전 버전의 Java를 사용하는 경우...Joda Time 및 을 사용할 수 있습니다.만약 당신이 정말로 기간을 가지고 있다면(즉, 캘린더 시스템을 참조하지 않고 경과된 시간) 당신은 아마도 다음을 사용해야 할 것이다.Duration - 그럼 - 라고 됩니다.toPeriod이든 지정)PeriodType이 되지 않는지 하여 25시간이 1시간, 1시간이 되는지 등을 알 수 .Period포맷할 수 있습니다.

8 이 i i i : 보보 java java java java java java java java java java java java java java java java java java java java java java java 를 사용하는 것을 추천합니다.java.time.Duration지속시간을 나타냅니다. 다음 '아까보다'로 전화를 됩니다.getSeconds()또는 필요에 따라 bobince의 답변에 따라 표준 문자열 포맷을 위한 정수를 얻을 수도 있습니다.단, 출력 문자열에 음의 기호가 1개 포함되어 있으면 좋기 때문에 지속시간이 음의 상황에 주의해야 합니다.예를 들어 다음과 같습니다.

public static String formatDuration(Duration duration) {
    long seconds = duration.getSeconds();
    long absSeconds = Math.abs(seconds);
    String positive = String.format(
        "%d:%02d:%02d",
        absSeconds / 3600,
        (absSeconds % 3600) / 60,
        absSeconds % 60);
    return seconds < 0 ? "-" + positive : positive;
}

이런 식으로 포맷하는 것은 귀찮을 정도로 수동적이긴 하지만 상당히 간단합니다.파싱은 일반적으로 더 어려운 문제가 됩니다.물론 Java 8에서도 Joda Time을 사용할 수 있습니다.

자바 9 a.Duration여전히 형식을 지정할 수는 없지만 시간, 분, 초를 가져오는 방법이 추가되어 작업이 다소 간단해집니다.

    LocalDateTime start = LocalDateTime.of(2019, Month.JANUARY, 17, 15, 24, 12);
    LocalDateTime end = LocalDateTime.of(2019, Month.JANUARY, 18, 15, 43, 33);
    Duration diff = Duration.between(start, end);
    String hms = String.format("%d:%02d:%02d", 
                                diff.toHours(), 
                                diff.toMinutesPart(), 
                                diff.toSecondsPart());
    System.out.println(hms);

이 스니펫의 출력은 다음과 같습니다.

24:19:21

long duration = 4 * 60 * 60 * 1000;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault());
log.info("Duration: " + sdf.format(new Date(duration - TimeZone.getDefault().getRawOffset())));

최소 24시간 미만의 지속 시간 동안 상당히 심플하고 우아한(IMO) 접근 방식이 있습니다.

DateTimeFormatter.ISO_LOCAL_TIME.format(value.addTo(LocalTime.of(0, 0)))

포맷터에는 포맷할 시간 객체가 필요하므로 Local Time 00:00(자정)에 기간을 추가하여 생성할 수 있습니다.그러면 자정부터 그 시각까지의 기간을 나타내는 LocalTime이 표시됩니다.이 시간은 표준 HH:mm:ss 표기로 쉽게 포맷할 수 있습니다.이는 외부 라이브러리가 필요하지 않다는 장점이 있으며 시간, 분, 초를 수동으로 계산하는 것이 아니라 java.time 라이브러리를 사용하여 계산을 수행합니다.

은 ""만 합니다.Duration 8: Java 8 에 methods and :

public static String format(Duration d) {
    long days = d.toDays();
    d = d.minusDays(days);
    long hours = d.toHours();
    d = d.minusHours(hours);
    long minutes = d.toMinutes();
    d = d.minusMinutes(minutes);
    long seconds = d.getSeconds() ;
    return 
            (days ==  0?"":days+" jours,")+ 
            (hours == 0?"":hours+" heures,")+ 
            (minutes ==  0?"":minutes+" minutes,")+ 
            (seconds == 0?"":seconds+" secondes,");
}

원하는지 모르겠지만 이 Android 도우미 클래스를 확인해 보세요.

import android.text.format.DateUtils

를 들면, '먹다'와 같이요.DateUtils.formatElapsedTime()

이것은 다소 진부할 수 있지만, Java 8을 사용하여 이를 달성하고자 한다면 좋은 해결책입니다.java.time:

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalField;
import java.time.temporal.UnsupportedTemporalTypeException;

public class TemporalDuration implements TemporalAccessor {
    private static final Temporal BASE_TEMPORAL = LocalDateTime.of(0, 1, 1, 0, 0);

    private final Duration duration;
    private final Temporal temporal;

    public TemporalDuration(Duration duration) {
        this.duration = duration;
        this.temporal = duration.addTo(BASE_TEMPORAL);
    }

    @Override
    public boolean isSupported(TemporalField field) {
        if(!temporal.isSupported(field)) return false;
        long value = temporal.getLong(field)-BASE_TEMPORAL.getLong(field);
        return value!=0L;
    }

    @Override
    public long getLong(TemporalField field) {
        if(!isSupported(field)) throw new UnsupportedTemporalTypeException(new StringBuilder().append(field.toString()).toString());
        return temporal.getLong(field)-BASE_TEMPORAL.getLong(field);
    }

    public Duration getDuration() {
        return duration;
    }

    @Override
    public String toString() {
        return dtf.format(this);
    }

    private static final DateTimeFormatter dtf = new DateTimeFormatterBuilder()
            .optionalStart()//second
            .optionalStart()//minute
            .optionalStart()//hour
            .optionalStart()//day
            .optionalStart()//month
            .optionalStart()//year
            .appendValue(ChronoField.YEAR).appendLiteral(" Years ").optionalEnd()
            .appendValue(ChronoField.MONTH_OF_YEAR).appendLiteral(" Months ").optionalEnd()
            .appendValue(ChronoField.DAY_OF_MONTH).appendLiteral(" Days ").optionalEnd()
            .appendValue(ChronoField.HOUR_OF_DAY).appendLiteral(" Hours ").optionalEnd()
            .appendValue(ChronoField.MINUTE_OF_HOUR).appendLiteral(" Minutes ").optionalEnd()
            .appendValue(ChronoField.SECOND_OF_MINUTE).appendLiteral(" Seconds").optionalEnd()
            .toFormatter();

}

다음은 기간을 포맷하는 방법의 예를 하나 더 보여드리겠습니다.이 샘플은 양의 지속 시간과 음의 지속 시간을 모두 양의 지속 시간으로 나타낸다는 점에 유의하십시오.

import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.MINUTES;
import static java.time.temporal.ChronoUnit.SECONDS;

import java.time.Duration;

public class DurationSample {
    public static void main(String[] args) {
        //Let's say duration of 2days 3hours 12minutes and 46seconds
        Duration d = Duration.ZERO.plus(2, DAYS).plus(3, HOURS).plus(12, MINUTES).plus(46, SECONDS);

        //in case of negative duration
        if(d.isNegative()) d = d.negated();

        //format DAYS HOURS MINUTES SECONDS 
        System.out.printf("Total duration is %sdays %shrs %smin %ssec.\n", d.toDays(), d.toHours() % 24, d.toMinutes() % 60, d.getSeconds() % 60);

        //or format HOURS MINUTES SECONDS 
        System.out.printf("Or total duration is %shrs %smin %sec.\n", d.toHours(), d.toMinutes() % 60, d.getSeconds() % 60);

        //or format MINUTES SECONDS 
        System.out.printf("Or total duration is %smin %ssec.\n", d.toMinutes(), d.getSeconds() % 60);

        //or format SECONDS only 
        System.out.printf("Or total duration is %ssec.\n", d.getSeconds());
    }
}

+H 중 하나를 반환하는 다음 함수는 어떻습니까?MM: SS 또는 +H:MM: SS.ss

public static String formatInterval(final long interval, boolean millisecs )
{
    final long hr = TimeUnit.MILLISECONDS.toHours(interval);
    final long min = TimeUnit.MILLISECONDS.toMinutes(interval) %60;
    final long sec = TimeUnit.MILLISECONDS.toSeconds(interval) %60;
    final long ms = TimeUnit.MILLISECONDS.toMillis(interval) %1000;
    if( millisecs ) {
        return String.format("%02d:%02d:%02d.%03d", hr, min, sec, ms);
    } else {
        return String.format("%02d:%02d:%02d", hr, min, sec );
    }
}

이것은 유효한 옵션입니다.

public static String showDuration(LocalTime otherTime){          
    DateTimeFormatter df = DateTimeFormatter.ISO_LOCAL_TIME;
    LocalTime now = LocalTime.now();
    System.out.println("now: " + now);
    System.out.println("otherTime: " + otherTime);
    System.out.println("otherTime: " + otherTime.format(df));

    Duration span = Duration.between(otherTime, now);
    LocalTime fTime = LocalTime.ofNanoOfDay(span.toNanos());
    String output = fTime.format(df);

    System.out.println(output);
    return output;
}

메서드를 호출하다

System.out.println(showDuration(LocalTime.of(9, 30, 0, 0)));

다음과 같은 것이 생성됩니다.

otherTime: 09:30
otherTime: 09:30:00
11:31:27.463
11:31:27.463

ISO-8601 표준에 근거해 모델화되어 JSR-310 실장의 일부로서 Java-8과 함께 도입된 것을 사용할 수 있습니다.Java-9에서는 몇 가지 편리한 방법이 도입되었습니다.

데모:

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Month;

public class Main {
    public static void main(String[] args) {
        LocalDateTime startDateTime = LocalDateTime.of(2020, Month.DECEMBER, 10, 15, 20, 25);
        LocalDateTime endDateTime = LocalDateTime.of(2020, Month.DECEMBER, 10, 18, 24, 30);

        Duration duration = Duration.between(startDateTime, endDateTime);
        // Default format
        System.out.println(duration);

        // Custom format
        // ####################################Java-8####################################
        String formattedElapsedTime = String.format("%02d:%02d:%02d", duration.toHours() % 24,
                duration.toMinutes() % 60, duration.toSeconds() % 60);
        System.out.println(formattedElapsedTime);
        // ##############################################################################

        // ####################################Java-9####################################
        formattedElapsedTime = String.format("%02d:%02d:%02d", duration.toHoursPart(), duration.toMinutesPart(),
                duration.toSecondsPart());
        System.out.println(formattedElapsedTime);
        // ##############################################################################
    }
}

출력:

PT3H4M5S
03:04:05
03:04:05

최신 날짜 API에 대한 자세한 내용은 Trail: Date Time을 참조하십시오.

  • 어떤 이유로든 Java 6 또는 Java 7을 고수해야 하는 경우 대부분의 java.time 기능을 Java 6 및7로 백포트하는 ThreeTen-Backport를 사용할 수 있습니다.
  • Android 프로젝트에서 일하고 있으며 Android API 레벨이 Java-8과 호환되지 않는 경우 Dissugaring과 How to Use ThreeTen을 통해 이용 가능한 Java 8+ API를 확인하십시오.Android Project의 ABP.

java8용으로 만드는 또 다른 방법이 있습니다.하지만 지속시간이 24시간을 넘지 않으면 효과가 있다.

public String formatDuration(Duration duration) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm.SSS");
    return LocalTime.ofNanoOfDay(duration.toNanos()).format(formatter);
}
String duration(Temporal from, Temporal to) {
    final StringBuilder builder = new StringBuilder();
    for (ChronoUnit unit : new ChronoUnit[]{YEARS, MONTHS, WEEKS, DAYS, HOURS, MINUTES, SECONDS}) {
        long amount = unit.between(from, to);
        if (amount == 0) {
            continue;
        }
        builder.append(' ')
                .append(amount)
                .append(' ')
                .append(unit.name().toLowerCase());
        from = from.plus(amount, unit);
    }
    return builder.toString().trim();
}

이 기능의 사용

private static String strDuration(long duration) {
    int ms, s, m, h, d;
    double dec;
    double time = duration * 1.0;

    time = (time / 1000.0);
    dec = time % 1;
    time = time - dec;
    ms = (int)(dec * 1000);

    time = (time / 60.0);
    dec = time % 1;
    time = time - dec;
    s = (int)(dec * 60);

    time = (time / 60.0);
    dec = time % 1;
    time = time - dec;
    m = (int)(dec * 60);

    time = (time / 24.0);
    dec = time % 1;
    time = time - dec;
    h = (int)(dec * 24);
    
    d = (int)time;
    
    return (String.format("%d d - %02d:%02d:%02d.%03d", d, h, m, s, ms));
}

한 요.java.time.Duration"CHANGE: "CHANGE:

duration.run {
   "%d:%02d:%02d.%03d".format(toHours(), toMinutesPart(), toSecondsPart(), toMillisPart())
}

예: " " "120:56:03.004

My Library Time4J는 패턴 기반 솔루션을 제공합니다(와 유사).Apache DurationFormatUtils 유연함 ,, 연, ,, 유, 유, ,, ,, ,, ,, ,, ,, ,.

Duration<ClockUnit> duration =
    Duration.of(-573421, ClockUnit.SECONDS) // input in seconds only
    .with(Duration.STD_CLOCK_PERIOD); // performs normalization to h:mm:ss-structure
String fs = Duration.formatter(ClockUnit.class, "+##h:mm:ss").format(duration);
System.out.println(fs); // output => -159:17:01

이 코드는 시간 오버플로 및 부호 처리를 처리하는 기능을 보여줍니다.패턴에 기반한 duration-formatter의 API도 참조하십시오.

scala(다른 시도도 봤지만 감명받지 못했습니다)

def formatDuration(duration: Duration): String = {
  import duration._ // get access to all the members ;)
  f"$toDaysPart $toHoursPart%02d:$toMinutesPart%02d:$toSecondsPart%02d:$toMillisPart%03d"
}

★★★★★★★★★★★★★★★★★?에 IDE를 호출할 수 합니다).$toHoursPart기타)는 다른 색입니다.

f"..."는 입니다.printf/String.format interpulator 문자열 인터폴레이터(변환))를할 수 .$의 합니다.1 14:06:32.583 , . . . . . . . .f보간 문자열은 다음과 같습니다.String.format("1 %02d:%02d:%02d.%03d", 14, 6, 32, 583)

, 분 에 ))))))))))))))(시간, 분 등)가 이 될 수 ..toFooPart()편리한 방법

예.

Duration.ofMinutes(110L).toMinutesPart() == 50

부모 단위의 다음 값(시간)까지 경과한 분수를 확인.

Scala에서는 간소화된 YourBestBet 솔루션을 기반으로 구축:

def prettyDuration(seconds: Long): List[String] = seconds match {
  case t if t < 60      => List(s"${t} seconds")
  case t if t < 3600    => s"${t / 60} minutes" :: prettyDuration(t % 60)
  case t if t < 3600*24 => s"${t / 3600} hours" :: prettyDuration(t % 3600)
  case t                => s"${t / (3600*24)} days" :: prettyDuration(t % (3600*24))
}

val dur = prettyDuration(12345).mkString(", ") // => 3 hours, 25 minutes, 45 seconds

scala에서는 라이브러리가 필요 없습니다.

def prettyDuration(str:List[String],seconds:Long):List[String]={
  seconds match {
    case t if t < 60 => str:::List(s"${t} seconds")
    case t if (t >= 60 && t< 3600 ) => List(s"${t / 60} minutes"):::prettyDuration(str, t%60)
    case t if (t >= 3600 && t< 3600*24 ) => List(s"${t / 3600} hours"):::prettyDuration(str, t%3600)
    case t if (t>= 3600*24 ) => List(s"${t / (3600*24)} days"):::prettyDuration(str, t%(3600*24))
  }
}
val dur = prettyDuration(List.empty[String], 12345).mkString("")

언급URL : https://stackoverflow.com/questions/266825/how-to-format-a-duration-in-java-e-g-format-hmmss

반응형