カウントダウン タイマーを作成しています。mm:dd:yyyy:hour:minute:sec の形式で 2 つの日付 (現在と終了日) があり、残りの時間を表示する必要があります。つまり、
終了日:時刻 - 現在です。日付時刻
両方の日付をミリ秒単位で変換し、減算してから日付に戻すことを考えましたが、それは面倒すぎるようです Javaでこれを効果的に実装するにはどうすればよいですか?
カウントダウン タイマーを作成しています。mm:dd:yyyy:hour:minute:sec の形式で 2 つの日付 (現在と終了日) があり、残りの時間を表示する必要があります。つまり、
終了日:時刻 - 現在です。日付時刻
両方の日付をミリ秒単位で変換し、減算してから日付に戻すことを考えましたが、それは面倒すぎるようです Javaでこれを効果的に実装するにはどうすればよいですか?
joda-time
フレームワークに任せる
String date = "02:13:2013:14:45:42"; // one of these is your end time
String date2 = "02:13:2013:14:45:49"; // the other gets smaller every time as you approach the end time
// 7 seconds difference
DateTimeFormatter format = DateTimeFormat.forPattern("MM:dd:yyyy:HH:mm:ss"); // your pattern
DateTime dateTime = format.parseDateTime(date);
System.out.println(dateTime);
DateTime dateTime2 = format.parseDateTime(date2);
System.out.println(dateTime2);
Duration duration = new Duration(dateTime, dateTime2);
System.out.println(duration.getMillis());
版画
2013-02-13T14:45:42.000-05:00
2013-02-13T14:45:49.000-05:00
7000
したがって、日付文字列をオブジェクトに解析し、DateTime
オブジェクトを使用しDuration
て時間単位で時差を計算します。
Interval
またはオブジェクトを使用することもできPeriod
ます (必要な精度によって異なります)。
System.out.println(duration.toPeriod().get(DurationFieldType.seconds()));
あなたが述べる
両方の日付をミリ秒単位で変換し、減算してから日付に戻すことを考えました
なぜそれらを元に戻す必要があるのでしょうか? あなたはすでにそれらを持っています。その間の時間に興味があるだけです。
Calendar until = Calendar.getInstance();
until.set("YYYY","DD","HH","MM","SS");
getTimeDifference(まで);
private String getTimeDifference(Calendar until) {
Calendar nowCal = (Calendar) until.clone();
nowCal.clear();
Date nowDate = new Date(System.currentTimeMillis());
nowCal.setTime(nowDate);
int sec = until.get(Calendar.SECOND) - nowCal.get(Calendar.SECOND);
int min = until.get(Calendar.MINUTE) - nowCal.get(Calendar.MINUTE);
int hrs = until.get(Calendar.HOUR) - nowCal.get(Calendar.HOUR);
String timeDiff = hrs+":"+min+":"+sec;
return timeDiff;
}