Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

java - Find total hours between two Dates

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.

When I use .toString() on my Date object I get this: Fri Dec 18 08:08:10 CST 2009

I've tried the following:

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.

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should work.

long secs = (this.endDate.getTime() - this.startDate.getTime()) / 1000;
int hours = secs / 3600;    
secs = secs % 3600;
int mins = secs / 60;
secs = secs % 60;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...