2017-01-03 9 views
0

Это, как я называю getTimeBetween функцию:Как получить разницу во времени между двумя ZonedDateTimes и довольно печатать ее как «4 часа, 1 минута, 40 секунд назад»?

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

И я надеюсь, этот вывод:

4 hours, 1 minute, 40 seconds ago 

Это моя getTimeBetween функция:

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

Благодарим вас за ответ. Это очень полезно. Кстати, я думаю, что «назад» и «в будущем» следует поменять местами. – Defozo

+0

@Defozo Это было предназначено - если дата 'from' перед датой' to' дата 'to' должна быть в будущем. Я думаю, вы могли бы поменять параметры: P – Moira

 Смежные вопросы

  • Нет связанных вопросов^_^