Javaで期間をフォーマットするにはどうすればよいですか?(例: H:MM:SS 形式)
-
06-07-2019 - |
質問
H:MM:SS のようなパターンを使用して時間を秒単位でフォーマットしたいと考えています。Java の現在のユーティリティは、時間をフォーマットするように設計されていますが、期間はフォーマットしません。
解決
8より前のバージョンのJavaを使用している場合は、 Joda Time および PeriodFormatter
。期間(つまり、経過時間、カレンダーシステムへの参照なし)を実際に取得している場合は、ほとんどの場合 Duration
を使用する必要があります-その後、を呼び出すことができますtoPeriod
(25時間が1日と1時間になるかどうかを反映する PeriodType
を指定するなど)して、フォーマット可能な Period
を取得します。
Java 8以降を使用している場合:通常、 java.time.Duration
を使用して期間を表すことをお勧めします。その後、必要に応じて getSeconds()
などを呼び出して、必要に応じてボビンスの回答に従って標準の文字列フォーマット用の整数を取得できます-ただし、期間が負の状況に注意する必要がありますおそらく、出力文字列に単一の負符号が必要です。次のようなものです:
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を使用できます。
他のヒント
ライブラリをドラッグしたくない場合は、Formatterまたは関連するショートカットを使用して簡単に実行できます。指定された整数の秒数s:
String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));
Apache commonの DurationFormatUtils のように:
DurationFormatUtils.formatDuration(millis, "**H:mm:ss**", true);
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())));
これはJava 9の方が簡単です。 Duration
はまだフォーマット可能な形式ではありません(私が知っていることですが)、時間、分、秒を取得するメソッドが追加され、タスクはやや簡単です:
Duration diff = // ...;
String hms = String.format("%d:%02d:%02d",
diff.toHoursPart(),
diff.toMinutesPart(),
diff.toSecondsPart());
これは一種のハッキングかもしれませんが、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();
}
これは、Java 7の新機能の1つになります
ここでは、期間をフォーマットする方法のもう 1 つのサンプルを示します。このサンプルでは、正の期間と負の期間の両方が正の期間として示されていることに注意してください。
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());
}
}
これは有効なオプションです。
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
次の関数はどうですか? + H:MM:SS または + H:MM:SS.sss
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 );
}
}
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();
}
この回答では、 Duration
メソッドのみを使用し、Java 8で動作します:
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,");
}
少なくとも24時間未満の場合は、かなりシンプルで(IMO)エレガントなアプローチがあります:
DateTimeFormatter.ISO_LOCAL_TIME.format(value.addTo(LocalTime.of(0、0)))
フォーマッターはフォーマットする一時オブジェクトを必要とするため、LocalTimeに00:00(真夜中)に期間を追加して作成することができます。これにより、真夜中からその時間までの期間を表すLocalTimeが得られ、標準のHH:mm:ss表記で簡単にフォーマットできます。これには、外部ライブラリを必要としないという利点があり、時間、分、秒を手動で計算するのではなく、java.timeライブラリを使用して計算を行います。
私のライブラリ 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パターンに基づく。
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("")
これは表示されなかったので、追加したいと思いました:
Date started=new Date();
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
task
long duration=new Date().getTime()-started.getTime();
System.out.println(format.format(new Date(duration));
24時間しか機能しませんが、通常はそれが必要です。