![](/img/trans.png)
[英]Find the difference in days between a java.util.Date and a Joda-Time DateTime?
[英]Find the exact difference between two (Joda Time) DateTime objects in java
我有兩個日期(其中一個是現在),需要找到兩者之間的差異。 我的代碼給了我糟糕的輸出(有時甚至是負面的)。
我已經嘗試過使用Months,Days,Seconds,Hours和Years類,並且在沒有運氣的方法之間使用。
編輯:返回原始代碼,但沒有持續時間。 @Basil Bourque發布了一個很好的解決方案,但我對Periods / Duration以及從它們動態格式化的所有方面都沒有足夠的經驗。
解
public static String formattedTime(DateTime d){
DateTime present = new DateTime(Calendar.getInstance());
//dont really want to deal with WHY its 7hrs ahead. o well
DateTime date = d.minusHours(7);
int diff = Seconds.secondsBetween(date,present).getSeconds();
String postfix = "s";
Log.i("time", "" + diff);
if(diff>59){
diff = Minutes.minutesBetween(date, present).getMinutes();
postfix = "s";
if(diff>59){
diff = Hours.hoursBetween(date, present).getHours();
postfix = "hr";
if(diff>1)
postfix+="s";
if(diff>23){
diff = Days.daysBetween(date, present).getDays();
postfix = "d";
if(diff>6){
diff = Weeks.weeksBetween(date, present).getWeeks();
postfix = "wk";
if(diff>1)
postfix+="s";
if(diff>3){
diff = Months.monthsBetween(date, present).getMonths();
postfix = "m";
if(diff>11){
diff = Years.yearsBetween(date, present).getYears();
postfix = "yr";
if(diff>1)
postfix+="s";
}
}
}
}
}
}
return diff+postfix;
}
你工作太辛苦了。 您正在使用錯誤的類來達到您的目的。
Period
類 在Joda-Time中,如果要將時間范圍表示為年,月,日,小時,分鍾,秒數,請使用Period
類。 Joda-Time以三種方式中的任何一種表示時間跨度: Interval
, Duration
或Period
。
Joda-Time遵循ISO 8601標准,用於解析和生成日期時間值的字符串表示。 對於期間,這意味着PnYnMnDTnHnMnS
格式,其中P
標記開頭,而T
將年 - 月 - 日部分與小時 - 分 - 秒部分分開。 一個半小時是PT30M
。 P3Y6M4DT12H30M5S
代表“三年,六個月,四天,十二小時,三十分鍾和五秒”。 搜索StackOverflow.com以獲取更多信息和示例。
如果要使用單詞進行漂亮打印,請查看PeriodFormatter
和PeriodFormatterBuilder
類。
如果需要整數,也可以向Period對象詢問各種組件編號。
此外,您應指定時區。 如果省略,則隱式應用JVM的當前默認時區。 最好明確指定您希望/期望的時區。
始終使用正確的時區名稱 ,從不使用3-4個字母代碼。 這些代碼既不標准也不獨特。 他們進一步混淆了夏令時(DST)的問題。
此外,通常服務器保持在UTC時區。 通常最好做幾乎所有業務邏輯,數據存儲,數據交換和UTC記錄。
請注意,您可以在不涉及java.util.Date對象的情況下詢問DateTime
當前時刻(如問題中所示)。
Period的示例代碼。
DateTimeZone zone = DateTimeZone.forID( "America/Detroit" ) ;
DateTime then = new DateTime( yourJUDate , zone ) ;
DateTime now = DateTime.now( zone ) ;
Period period = new Period( then , now ) ;
你可以在這里看到答案: 兩個日期之間的天數,並根據你想要的單位進行調整。
制作兩個相互比較的字符串,您可以使用String#split()方法將其拆分以查找年/月/日等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.