簡體   English   中英

如何使用 JodaTime 以毫秒為單位獲取 2 個日期之間的時間差

[英]How to get the time difference between 2 dates in millisec using JodaTime

我將設計一個應用程序,我需要在其中獲取兩個日期之間的確切時間差。 前任:

Date1:31/05/2011 12:54:00
Date2:31/05/2011 13:54:00

我嘗試使用getTime()但我沒有得到確切的結果。

上述輸入的預期 output 為3600000 (60 * 60 * 1000) 毫秒,但我得到46800000 (13 * 60 * 60 * 1000)。

當我瀏覽不同的 java 論壇時,人們建議使用 JodaTime。

我仍然無法得到確切的結果。

我工作的時區是倫敦(格林威治標准時間)。

初始化兩個 dateTime 並使用 Period:

DateTime dt1 = new DateTime(2013,9,11,9,58,56);
DateTime dt2 = new DateTime(2013,9,11,9,58,59);
Period p = new Period(dt1, dt2, PeriodType.millis());

以毫秒為單位獲得差異:

System.out.println(p.getValue(0));
public static long getDiff(Calender cal1, Calender cal2)
{
    return Math.abs(cal1.getTimeInMillis() - cal2.getTimeInMillis());
}

查看secondsBetween( )

創建一個 Seconds,表示兩個指定的部分日期時間之間的整秒數。 這兩個部分必須包含相同的字段,例如您可以指定兩個 LocalTime 對象。

參數:

 start - the start partial date, must not be null
    end - the end partial date, must not be null 

回報:

 the period in seconds 

JodaTime 在內部使用機器時間。 因此,要查找毫秒,您可以使用存儲 LocalDateTime 的常量來表示 1970 年 1 月 1 日(因為UNIX 時間)。

Unix 時間或 POSIX 時間是一種用於描述時間點的系統,定義為自 1970 年 1 月 1 日午夜預測協調世界時 (UTC) 以來經過的秒數,不包括閏秒。 然后計算您的 DateTime 之間的差異。

我試過這樣;

public static void main(String[] args) {
        final LocalDateTime JAN_1_1970 = new LocalDateTime(1970, 1, 1, 0, 0);
        DateTime local = new DateTime().withZone(DateTimeZone.forID("Europe/Amsterdam"));
        DateTime utc = new DateTime(DateTimeZone.UTC);

        System.out.println("Europe/Amsterdam milis :" + new Duration(JAN_1_1970.toDateTime(DateTimeZone.forID("Europe/Amsterdam")), local).getMillis());
        System.out.println("UTC  milis             :" + new Duration(JAN_1_1970.toDateTime(DateTimeZone.UTC), utc).getMillis());

    }

結果是;

Europe/Amsterdam milis :1429695646528
UTC  milis             :1429692046534

@leonbloy 在這里寫一個很好的評論。

您的 local 和 UTC 代表相同的時間瞬間(僅附有不同的時區)。 因此,getMillis()(給出從對應於 unix 紀元的“瞬間”經過的“物理”時間間隔)必須返回相同的值。

Joda 是一個完美的庫,但如果您需要以毫秒為單位的 2 個日期之間的差異,您只需計算 getTime() 之間的差異。 如果你得到錯誤的結果,你會遇到一些時區問題。 通常它會起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM