gpt4 book ai didi

android - 计算2天android之间的时差

转载 作者:行者123 更新时间:2023-11-30 01:12:25 25 4
gpt4 key购买 nike

我正在尝试计算 2 次之间的差异。它运作良好,除非两个日期分别在午夜的每一侧。在那种情况下,我得到否定的答案。我有什么想法可以改进代码来解决这个问题吗?

String sleepStart = editFallAsleepTime.getText().toString();
String sleepStop = editWakeUpTime.getText().toString();
String awakeTimeString = ((Globals) getActivity().getApplication()).getAwakeTime();

//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("HH:mm");

Date d1 = null;
Date d2 = null;

try
{
d1 = format.parse(sleepStart);
d2 = format.parse(sleepStop);

float t1 = d1.getTime();
float t2 = d2.getTime();

if( t2 <= t1 ){
t2 +=24;
}

float diff = t2 - t1;

//in milliseconds
float diff = d2.getTime() - d1.getTime();
float diffHours = diff / (60 * 60 * 1000);
float awakeTime = Float.valueOf(awakeTimeString);
float awakeHours = awakeTime / 60;
float calcEffectiveSleep = diffHours - awakeHours;
String sleepTime = Float.toString(diffHours);
String effectiveSleep = Float.toString(calcEffectiveSleep);
((Globals) getActivity().getApplication()).setEffectiveSleep(effectiveSleep);
}
catch (Exception e)
{
Log.e("timediff","didntwork");
}

最佳答案

如果您的差异小于 1 天,那么您可以考虑像@Andre Classen 所说的那样处理 d2 < d1 的情况。做法是:

t1 = d1.getTime();
t2 = d2.getTime();

if( t2 <= t1 ){
t2 +=24*60*60*1000;
}

diff = t2 - t1;

关于android - 计算2天android之间的时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38287051/

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