问题描述
我有两个Date对象,我需要得到时间差,这样我就可以确定它们之间的总小时数。他们碰巧是在同一天。我希望得到的结果是小时和分钟。
I have two Date objects and I need to get the time difference so I can determine the total hours between them. They happen to be from the same day. The result I would like would have the hours and minutes.
当我在我的Date对象上使用.toString()时,我得到这个:Fri Dec 18 08:08:10 CST 2009
When I use .toString() on my Date object I get this: Fri Dec 18 08:08:10 CST 2009
我尝试了以下内容:
long diff=(this.endDate.getTime()-this.startDate.getTime())/(60*60 * 1000);
但这只给我几小时,而不是分钟。
我知道这是一个简单的问题,但我无法理解它。
But this only gives me hours, not the minutes.I know this is a simple problem, but I can't figure it out atm.
编辑:
对于那些感兴趣的人的最终解决方案。感谢Michael Brewer-Davis
Edits:Final solution for those interested. Thanks to Michael Brewer-Davis
Period p = new Period(this.startDate, this.endDate);
long hours = p.getHours();
long minutes = p.getMinutes();
String format = String.format("%%0%dd", 2);
return Long.toString(hours)+":"+String.format(format, minutes);
推荐答案
以下是:
DateTime startTime, endTime;
Period p = new Period(startTime, endTime);
int hours = p.getHours();
int minutes = p.getMinutes();
您可以使用Joda的格式化程序格式化,例如PeriodFormat,但我建议使用Java。有关详细信息,请参见。
You could format with Joda's formatters, e.g., PeriodFormat, but I'd suggest using Java's. See this question for more details.
这篇关于查找两个日期之间的总小时数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!