簡體   English   中英

在 Java 中用時間執行 A - B (A\\B)?

[英]Perform A - B (A\B) with Time in java?

如果我有這個代碼:

DateTime start = new DateTime().withTime(4, 0, 0, 0);
DateTime end = start.withTime(5, 0, 0, 0);

DateTime s2 = start.withTime(4,30,0,0);
DateTime e2 = start.withTime(5,30,0,0);

Duration d1 = new Duration(start,end);
Duration d2 = new Duration(s2,e2);

Duration result = d1.minus(d2);
System.out.println((int)result.getStandardMinutes());

有沒有辦法基本上可以得到 A - B 或 A \\ B (集合理論符號)? 在這種情況下,結果將是 30,因為第一個持續時間有 30 分鍾,而第二個持續時間沒有發生。

我不是專門在 Jodatime 中尋找解決方案,只是用它來解釋問題。

Duration表示時間量(例如"10 分 30 秒" ),但它沒有附加到時間線:10 分 30 秒相對於什么? 沒什么特別的,這只是時間(值)本身。

特別是在 Joda-Time 中,在創建Duration ,對象本身不存儲用於計算它的參考日期,因此Duration實例無法知道它是在特定日期之前還是之后(因為它是一段不附加到任何特定日期,因此您無法將其與日期進行比較)。

如果要考慮特定日期(在另一個日期之后或之前),並使用此日期來計算持續時間,則必須計算持續時間之前檢查日期:

// ignore dates before the start
DateTime date1 = s2.isBefore(start) ? start : s2;

// ignore dates after the end
DateTime date2 = e2.isAfter(end) ? end : e2;

Duration d2 = new Duration(date1, date2);

或者,你可以做你已經在做的事情,但最后,你檢查s2e2是否在開始/結束間隔之外,並將各自的持續時間添加回結果:

if (s2.isBefore(start)) {
    result = result.plus(new Duration(s2, start));
}
if (e2.isAfter(end)) {
    result = result.plus(new Duration(end, e2));
}

不確定集合論是否真的適用於此,但我可能是錯的(我不是數學專業人士)。

暫無
暫無

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

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