これは私がgetTimeBetween
関数を呼び出す方法です:2つの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を使用しています。
より良い方法:1) 'StringBuilder'を使用してください。 2)ヘルパーメソッドに対する共通コード、すなわち4つの「if」ステートメントをリファクタリングする。 – Andreas