gpt4 book ai didi

android - 如何在android中以天,小时(24),分钟(60),秒(60)获取两个日期之间的差异

转载 作者:行者123 更新时间:2023-11-29 16:42:25 25 4
gpt4 key购买 nike

如何计算两个日期之间的天数、小时数 (24)、分钟数 (60)、秒数 (60)。

我经历过

Android difference between Two Dates

How do I get difference between two dates in android?, tried every thing and post

但没有帮助,

这是我的代码..

  try {
String FinalDate = "20-04-2018 08:00:00";
String CurrentDate = "26-04-2018 10:10:30";
Date date1;
Date date2;

SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);

/*long difference = date1.getTime() - date2.getTime();
long differenceInMinutes = difference / (60 * 1000);
long differenceInSeconds = difference / 1000;
String strMinuteDifference = Long.toString(differenceInMinutes);
String strSecondsDifference = Long.toString(differenceInSeconds);*/

long difference = date1.getTime() - date2.getTime();
long seconds = difference / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;


Log.e("TAG_5", "CurrentDate is : " + date1);
Log.e("TAG_5", "Final date is : " + date2);
Log.e("TAG_5", "Day Difference: " + days);
Log.e("TAG_5", "hours Difference: " + hours);
Log.e("TAG_5", "Minute Difference: " + minutes);
Log.e("TAG_5", "Seconds Difference: " + seconds);


} catch (Exception exception) {
Log.e("TAG_5", "exception " + exception);
}

输出是

        E/TAG_5: CurrentDate is : Thu Apr 26 10:10:30 GMT+05:30 2018
E/TAG_5: Demo date is : Fri Apr 20 08:00:00 GMT+05:30 2018
E/TAG_5: Day Difference: 6
E/TAG_5: hours Difference: 146
E/TAG_5: Minute Difference: 8770
E/TAG_5: Seconds Difference: 526230

代码似乎是计算这两个日期之间的所有小时、分钟、秒,但是

我希望输出像...小时应该是 2 小时、10 小时或 23 小时,但不能超过 24 小时,因为 25 小时将是新的一天,所以应该是 1 天 1 小时。

和分钟像 10 分钟 35 分钟或 59 分钟,但不超过 60

Seconds 也一样,应该是 12 秒、40 秒或 59 秒,但不能超过 60 秒。 那么我该如何实现呢?

最佳答案

像你说的那样计算“休息”时间。 (所以不到 24 小时)您可以使用模数。

In computing, the modulo operation finds the remainder after division of one number by another (sometimes called modulus).

int hours = theAmountOfHours % 24

在你的例子中

Log.e("TAG_5", "Day Difference: " + days);
Log.e("TAG_5", "hours Difference: " + hours % 24);
Log.e("TAG_5", "Minute Difference: " + minutes % 60);
Log.e("TAG_5", "Seconds Difference: " + seconds % 60);

来源:Wikipedia

关于android - 如何在android中以天,小时(24),分钟(60),秒(60)获取两个日期之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50036253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com