2つのJava日付インスタンスの差を計算する 質問する

2つのJava日付インスタンスの差を計算する 質問する

私はjava.util.DateScala で Java のクラスを使用しており、オブジェクトと現在の時刻を比較したいと考えていますDate。getTime() を使用してデルタを計算できることはわかっています。

(new java.util.Date()).getTime() - oldDate.getTime()

しかし、これではミリ秒を表すものしか残りませんlong。時間差を取得する、もっと簡単で良い方法はあるでしょうか?

ベストアンサー1

シンプルな diff (ライブラリなし)

/**
 * Get a diff between two dates
 * @param date1 the oldest date
 * @param date2 the newest date
 * @param timeUnit the unit in which you want the diff
 * @return the diff value, in the provided unit
 */
public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
    long diffInMillies = date2.getTime() - date1.getTime();
    return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
}

そして次のように呼び出すことができます:

getDateDiff(date1,date2,TimeUnit.MINUTES);

2 つの日付の差分を分単位で取得します。

TimeUnitjava.util.concurrent.TimeUnitは、ナノ秒から日数までの標準 Java 列挙型です。


人間が読める diff (ライブラリなし)

public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) {

    long diffInMillies = date2.getTime() - date1.getTime();

    //create the list
    List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
    Collections.reverse(units);

    //create the result map of TimeUnit and difference
    Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
    long milliesRest = diffInMillies;

    for ( TimeUnit unit : units ) {
        
        //calculate difference in millisecond 
        long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
        long diffInMilliesForUnit = unit.toMillis(diff);
        milliesRest = milliesRest - diffInMilliesForUnit;

        //put the result in the map
        result.put(unit,diff);
    }

    return result;
}

http://ideone.com/5dXeu6

出力はMap:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0}、単位が順序付けられた のようになります。

そのマップをユーザーフレンドリーな文字列に変換するだけです。


警告

上記のコードスニペットは、2つの瞬間の単純な差分を計算します。夏時間への切り替え時に問題が発生する可能性があります。この郵便受けつまり、時間のない日付間の差分を計算すると、日/時間が欠落する可能性があります。

私の意見では、日付の違いは、特に曜日に関しては、主観的なものです。次のことが可能です。

  • 24時間の経過時間を数えます: 日+1 - 日 = 1 日 = 24時間

  • 経過時間をカウントします。夏時間を考慮します。日+1 - 日 = 1 = 24 時間 (ただし、真夜中の時間と夏時間を使用すると、0 日と 23 時間になる可能性があります)

  • の数を数えますday switches。経過時間が 2 時間 (夏時間の場合は 1 時間 :p) であっても、日 +1 午後 1 時 - 日 午前 11 時 = 1 日となります。

私の回答は、日数による日付の差の定義が最初のケースと一致する場合有効です。

JodaTimeで

JodaTime を使用している場合は、次のようにして 2 つのインスタント (ミリ秒単位の ReadableInstant) の日付の差分を取得できます。

Interval interval = new Interval(oldInstant, new Instant());

ただし、ローカルの日付/時刻の差分を取得することもできます。

// returns 4 because of the leap year of 366 days
new Period(LocalDate.now(), LocalDate.now().plusDays(365*5), PeriodType.years()).getYears() 

// this time it returns 5
new Period(LocalDate.now(), LocalDate.now().plusDays(365*5+1), PeriodType.years()).getYears() 

// And you can also use these static methods
Years.yearsBetween(LocalDate.now(), LocalDate.now().plusDays(365*5)).getYears()

おすすめ記事