잡동사니

반응형

질문

서버에서 시간 목록을 가져 오는 중이며 총 소요 시간을 표시하기 위해 추가하고 싶습니다. 하지만 방법을 찾을 수 없습니다. 시간은 평범한 문장과 같기 때문입니다.

15 min 24 s
1 min 56 s
18 min 3 s
2 h 48 min 46 s

이 데이터를 추가하는 방법은 무엇입니까?


답변1

tl; dr

표준 ISO 8601 입력 문자열과 함께 java.time.Durationclass를 사용하십시오.

Duration total = 
    Duration
    .parse(
        "PT" + 
        "2 h 48 min 46 s"
        .replace( "h" , "H" ) 
        .replace( "min" , "M" )
        .replace( "s" , "S" ) 
        .replace( " " , "" )    
    )
    .plus(
         another `Duration` object
    )

ISO 8601

날짜-시간 통신을위한 다양한 형식을 정의하는 ISO 8601 표준에 대해 해당 데이터의 게시자를 교육합니다. 값을 텍스트로.

타임 라인에 첨부되지 않은 표준 기간 동안의 형식 PnYnMnDTnHnMnS <입니다. / code> 여기서 P 는 시작을 표시하고 ( "기간"을 "p"로 간주) T 는 모든 년-월-일을 시간과 구분합니다. 분-초.

입력 변환

예제 입력은 ISO 8601 형식으로 변환 될 수 있습니다.

min M 으로 바꿉니다. h H 로 바꿉니다. 그리고 s S 로 바꿉니다.

또한 모든 SPACE 문자를 삭제하십시오. PT 를 앞에 추가합니다.

String input = "2 h 48 min 46 s" ;
String inputIso8601 = 
        "PT" + 
        input
        .replace( "h" , "H" ) 
        .replace( "min" , "M" )
        .replace( "s" , "S" ) 
        .replace( " " , "" )      
;

기간

Java의 최신 java.time class에는 기간. 이 class는 시간-분-초 단위로 타임 라인에 연결되지 않은 시간 범위를 나타냅니다.

이 class는 표준 ISO 8601 형식으로 문자열을 파싱하고 생성하는 방법을 알고 있습니다.

Duration d = Duration.parse( inputIso8601 ) ;

이 수업은 또한 수학을 수행하고 기간을 더하고 빼는 방법을 알고 있습니다.

Duration dTotal = d1.plus( d2 ) ;

그 변환 코드의 방법을 만들어 봅시다.

public String convertInputToIso8601 ( String input )
{
    String inputIso8601 =
            "PT" +
                    input
                            .replace( "h" , "H" )
                            .replace( "min" , "M" )
                            .replace( "s" , "S" )
                            .replace( " " , "" );
    return inputIso8601;
}

예제 입력을 사용하겠습니다.

    List < String > inputs = List.of(
            "15 min 24 s" ,
            "1 min 56 s" ,
            "18 min 3 s" ,
            "2 h 48 min 46 s"
    );

해당 입력의 형식 변환을 테스트하십시오.

    List < String > inputsIso8601 = 
        inputs
        .stream()
        .map( this :: convertInputToIso8601 )
        .collect( Collectors.toList() )
    ;

콘솔에 덤프합니다.

    System.out.println(
            inputsIso8601
    );

[PT15M24S, PT1M56S, PT18M3S, PT2H48M46S]

좋아 보인다. 이제 Duration객체로 파싱합니다.

    List < Duration > durations = 
        inputsIso8601
        .stream()
        .map( Duration :: parse )
        .collect( Collectors.toList() )
    ;

콘솔에 덤프합니다.

    System.out.println( durations );

[PT15M24S, PT1M56S, PT18M3S, PT2H48M46S]

그것도 좋아 보인다. 이제 수학을하십시오. java.time class는 불변 객체 를 사용합니다. 이것은 우리의 수학 연산이 원본을 변경 (변형)하는 것이 아니라 새로운 새로운 객체를 생성한다는 것을 의미합니다.

기존 구문을 사용하여 기간을 합산합니다.

    Duration total = Duration.ZERO;
    for ( Duration duration : durations )
    {
        total = total.plus( duration );
    }

스트림을 사용하여 기간 합계.

Duration total = 
    durations
    .stream()
    .reduce(
        Duration.ZERO , 
        Duration::plus
    )
;

콘솔에 덤프합니다.

    System.out.println( "total = " + total );

합계 = PT3H24M9S

작동했습니다. 귀하의 입력은 거의 3 시간 30 분입니다.

여기에 그 코드가 있습니다.

    List < String > inputs = List.of(
            "15 min 24 s" ,
            "1 min 56 s" ,
            "18 min 3 s" ,
            "2 h 48 min 46 s"
    );

    List < String > inputsIso8601 = inputs.stream().map( this :: convertInputToIso8601 ).collect( Collectors.toList() );
    System.out.println( inputsIso8601 );

    List < Duration > durations = inputsIso8601.stream().map( Duration :: parse ).collect( Collectors.toList() );
    System.out.println( durations );

    Duration total = durations.stream().reduce( Duration.ZERO , Duration::plus ) ;

    System.out.println( "total = " + total );

이 세 가지 스트리밍 문을 하나의 문으로 결합 할 수 있다고 생각합니다. 그러나 읽기와 디버깅은 더 어려울 것입니다.


java.time 정보

< em> java.time 프레임워크는 Java 8 이상에 내장되어 있습니다. 이러한 class는 레거시 날짜-시간 class를 대체합니다. //docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Date.html "rel ="nofollow noreferrer "> java.util.Date , 캘린더, & SimpleDateFormat.

자세한 내용은 Oracle 자습서 . 그리고 많은 예제와 설명을 위해 Stack Overflow를 검색하십시오. 사양은 JSR 310 입니다.

Joda-Time 프로젝트, 현재 유지 관리 모드 java.time class.

java.time 객체를 데이터베이스와 직접 교환 할 수 있습니다. JDBC 드라이버 사용 / jeps / 170 "rel ="nofollow noreferrer "> JDBC 4.2 이상. 문자열, java.sql. *class가 필요하지 않습니다.

java.time class는 어디서 구할 수 있습니까?



 

 

 

 

출처 : https://stackoverflow.com/questions/60802046/how-to-add-a-series-of-string-inputs-that-each-represent-a-span-of-time-in-andr

반응형

이 글을 공유합시다

facebook twitter googleplus kakaoTalk kakaostory naver band