gpt4 book ai didi

android - 如何在android中获得两次时间之间的分钟差

转载 作者:行者123 更新时间:2023-11-29 19:53:22 24 4
gpt4 key购买 nike

public int difftime(String string, String string2) {
int hours;
int min = 0;
int days;
long difference ;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
Date date1 = simpleDateFormat.parse("08:00 AM");
Date date2 = simpleDateFormat.parse("04:00 PM");

difference = date2.getTime() - date1.getTime();
days = (int) (difference / (1000 * 60 * 60 * 24));
hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours))
/ (1000 * 60);
hours = (hours < 0 ? -hours : hours);
Log.i("======= Hours", " :: " + hours);
return min;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return min;
}

这是我的函数,以分钟的形式获取时差,但它始终为零。我不知道我哪里做错了请告诉我哪里做错了。 我想要分钟形式的结果。

最佳答案

首先,你犯了非常基本的错误。 对于 12 小时制,您应该使用 hh 而不是 HH。我很惊讶地看到,没有一个答案可以纠正这个错误。

其次,您没有考虑日期,而只是根据时间来考虑。 所以 08:00AM 和 04:00PM 没有任何分钟差异。只有8小时的时差。

因此,现在在您的情况下,您必须根据两种情况计算分钟数,即一种来自小时数,另一种情况下存在分钟数差异。我更正你的代码。请检查它,因为这在我这边按预期工作。

public long diffTime() {
long min = 0;
long difference ;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm aa"); // for 12-hour system, hh should be used instead of HH
// There is no minute different between the two, only 8 hours difference. We are not considering Date, So minute will always remain 0
Date date1 = simpleDateFormat.parse("08:00 AM");
Date date2 = simpleDateFormat.parse("04:00 PM");

difference = (date2.getTime() - date1.getTime()) / 1000;
long hours = difference % (24 * 3600) / 3600; // Calculating Hours
long minute = difference % 3600 / 60; // Calculating minutes if there is any minutes difference
min = minute + (hours * 60); // This will be our final minutes. Multiplying by 60 as 1 hour contains 60 mins
} catch (Throwable e) {
e.printStackTrace();
}
return min;
}

关于android - 如何在android中获得两次时间之间的分钟差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36913996/

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