android计算固定日期和现在之间的差异



计算2013年1月1日和现在之间的差异的最佳方法是什么,因此结果看起来像25天16小时18分43秒?

String dateStop = "01.01.2013";
long now = System.currentTimeMillis():
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");  

Date d1 = null;
Date d2 = null;
try {
d1 = new Date (now);
d2 = format.parse(dateStop);
} catch (ParseException e) {
e.printStackTrace();
}   
long difference = d2.getTime() - d1.getTime();
long differenceBack = difference;
differenceBack = difference / 1000;
int secs = differenceBack % 60;
differenceBack /= 60;
int mins = differenceBack % 60;
differenceBack /= 60;
int hours = differenceBack % 24;

差异以毫秒为单位。然后你可以简单地用一些数学来计算天/小时/分钟/秒的

由于您还没有提供任何代码,我不会只为您做这件事,但由于各种原因(首先是时区),时间可能是一个有趣的话题。

我建议你建一个很棒的图书馆http://joda-time.sourceforge.net/

Joda Time提供了Java日期和时间的优质替代品类。该设计允许使用多个日历系统,同时提供简单的API。"默认"日历是ISO8601标准其由XML使用。格里高利、儒略、佛教徒、科普特人,埃塞俄比亚和伊斯兰体系也包括在内,我们欢迎进一步添加。支持课程包括时区、持续时间、格式和解析。

看看使用Periods和类似的东西

DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0);
DateTime end = new DateTime(2006, 1, 1, 0, 0, 0, 0);
// period of 1 year and 7 days
Period period = new Period(start, end);

我用了类似的东西来创建倒计时时钟,但你在问题中没有说明你想要返回的值的格式(天、秒、分钟)。然而,周期在这方面相当灵活。例如:

// able to calculate whole days between two dates easily
Days days = Days.daysBetween(start, end);
// able to calculate whole months between two dates easily
Months months = Months.monthsBetween(start, end);

最新更新