2017-01-03 5 views
0

이것은 내가 getTimeBetween 함수를 호출하는 방법입니다두 ZonedDateTimes 사이의 시간차를 어떻게 "4 시간, 1 분, 40 초 전"처럼 예쁜 것으로 인쇄합니까?

getTimeBetween(ZonedDateTime.now().minusHours(4).minusMinutes(1).minusSeconds(40), ZonedDateTime.now()); 

을 그리고 난이 출력 예상 : 이것은 내 getTimeBetween 기능

4 hours, 1 minute, 40 seconds ago 

입니다 : 예상하지만 그대로

private String getTimeBetween(ZonedDateTime zonedDateTime1, ZonedDateTime zonedDateTime2) { 
    Duration timeDifference = Duration.between(zonedDateTime1, zonedDateTime2); 
    if (timeDifference.getSeconds() == 0) return "now"; 
    String timeDifferenceAsPrettyString = ""; 
    Boolean putComma = false; 
    if (timeDifference.toDays() > 0) { 
     if (timeDifference.toDays() == 1) timeDifferenceAsPrettyString += timeDifference.toDays() + " day"; 
     else timeDifferenceAsPrettyString += timeDifference.toDays() + " days"; 
     putComma = true; 
    } 
    if (timeDifference.toHours() > 0) { 
     if (putComma) timeDifferenceAsPrettyString += ", "; 
     if (timeDifference.toHours() == 1) timeDifferenceAsPrettyString += timeDifference.toHours() + " hour"; 
     else timeDifferenceAsPrettyString += timeDifference.toHours() % 24 + " hours"; 
     putComma = true; 
    } 
    if (timeDifference.toMinutes() > 0) { 
     if (putComma) timeDifferenceAsPrettyString += ", "; 
     if (timeDifference.toMinutes() == 1) timeDifferenceAsPrettyString += timeDifference.toMinutes() + " minute"; 
     else timeDifferenceAsPrettyString += timeDifference.toMinutes() % 60 + " minutes"; 
     putComma = true; 
    } 
    if (timeDifference.getSeconds() > 0) { 
     if (putComma) timeDifferenceAsPrettyString += ", "; 
     if (timeDifference.getSeconds() == 1) timeDifferenceAsPrettyString += timeDifference.getSeconds() + " second"; 
     else timeDifferenceAsPrettyString += timeDifference.getSeconds() % 60 + " seconds"; 
    } 
    timeDifferenceAsPrettyString += " ago"; 
    return timeDifferenceAsPrettyString; 
} 

이 기능은 작동 이런 식으로하는 것이 정말 필요할까요? 아마도 이것을 달성하는 더 좋은 방법이 있을까요?

저는 Java 8을 사용하고 있습니다.

+0

더 나은 방법 : 1)'StringBuilder'를 사용하십시오. 2) 공통 코드를 도우미 메소드, 즉 네 개의 'if'문으로 리팩터링합니다. – Andreas

답변

1

어때요?

static String getTimeBetween(ZonedDateTime from, ZonedDateTime to) { 
    StringBuilder builder = new StringBuilder(); 
    long epochA = from.toEpochSecond(), epochB = to.toEpochSecond(); 
    long secs = Math.abs(epochB - epochA); 
    if (secs == 0) return "now"; 
    Map<String, Integer> units = new LinkedHashMap<>(); 
    units.put("day", 86400); 
    units.put("hour", 3600); 
    units.put("minute", 60); 
    units.put("second", 1); 
    boolean separator = false; 
    for (Map.Entry<String, Integer> unit : units.entrySet()) { 
     if (secs >= unit.getValue()) { 
      long count = secs/unit.getValue(); 
      if (separator) builder.append(", "); 
      builder.append(count).append(' ').append(unit.getKey()); 
      if (count != 1) builder.append('s'); 
      secs %= unit.getValue(); 
      separator = true; 
     } 
    } 
    return builder.append(epochA > epochB ? " ago" : " in the future").toString(); 
} 

당신은 아마 대신에게 모든 메소드 호출을 인스턴스화의 LinkedHashMap을 저장할 수 있지만, 이것은 작동합니다.

+0

답변 해 주셔서 감사합니다. 매우 도움이됩니다. BTW 나는 "이전"과 "미래"를 바꿔야한다고 생각합니다. – Defozo

+0

@Defozo 의도 된대로 - from 날짜가 to 날짜 이전 인 경우 to 날짜는 미래에 있어야합니다. 나는 당신이 매개 변수를 바꿀 수 있다고 생각한다 : P – Moira