簡體   English   中英

如何在天數,小時數,分鍾數和秒數之間獲得2個日期之間的差異

[英]How to get difference between 2 dates in number of days,hours,minutes and seconds

我希望獲得兩個給定日期之間的天數,小時數和分鍾數,到目前為止,我已經嘗試了3種不同的方式,但沒有一個給我正確的值。請告訴我如何獲得兩者之間的天數,小時數和分鍾數。 2給定日期。

在所有方面輸入estdate是星期六2月21日12:00:00 IST 2015 第1路

Date estDate=//date object which returns Sat Feb 21 12:00:00 IST 2015
long estDateInLong=estDate.getTime();
    long currentTimeinLong=Calendar.getInstance().getTimeInMillis();
    Long diff=currentTimeinLong-estDateInLong;
    long diffSeconds = diff / 1000 % 60;  //gives 6
    long diffMinutes = diff / (60 * 1000) % 60; //gives 21
    long diffHours=diff/(60*60 * 1000) % 60;//gives 26
    long diffDay=diff/(24*60*60 * 1000) % 60;//gives 16

這是錯的,所以我再次嘗試以下方式

Period p=new Period(new LocalDate(estDate)), new LocalDate(currentDate);
System.out.println(p.getDays());System.out.println(p.getHours());System.out.println(p.getMinutes());

輸出中

2
0
0

第三種方式

int delayTimeInDays=Days.daysBetween(new LocalDate(estDate), new LocalDate(currentDate).getDays();
    int delayTimeinHours=Hours.hoursBetween(new LocalDate(estDate), new LocalDate(currentDate).getHours();
    int seconds=Seconds.secondsBetween(new LocalDate(estDate), new LocalDate(currentDate)).getSeconds();

這給了我16,384,1382400

這又是錯的。

預期產出

當前時間是3月9日下午2點48分

從2015年2月21日中午12點到22日中午12點:1天

從2015年2月22日中午12點到23點12點中午:2天

所以直到今天中午12點= 16天

小時數= 2

分鍾數= 50

如果我的問題正確,那么這就是你要找的

long estDateInLong=//whatever gives you past date
long currentTimeinLong=Calendar.getInstance().getTimeInMillis();
long diff=(long)(currentTimeinLong-estDateInLong);
long diffDay=diff/(24*60*60 * 1000);
diff=diff-(diffDay*24*60*60 * 1000); //will give you remaining milli seconds relating to hours,minutes and seconds
long diffHours=diff/(60*60 * 1000);
diff=diff-(diffHours*60*60 * 1000); 
long diffMinutes = diff / (60 * 1000);
diff=diff-(diffMinutes*60*1000);
long diffSeconds = diff / 1000;
diff=diff-(diffSeconds*1000);       
System.out.println(diffDay +"\t"+diffHours+"\t"+diffMinutes+"\t"+diffSeconds);

使用Joda可能很容易做到(可能是!),但也可以這樣做

希望這可以幫助! 祝好運

暫無
暫無

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

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