简体   繁体   English

计算一天中两次之间的小时差异

[英]Calculate Hour Difference Between Two Times In a Day(s)

Just wanted to know if this function's results will always hold? 只是想知道这个功能的结果是否总能保持?

private int calcHourDiff(int start, int end) {

    int diff;

    if(start > end) {
        diff = ((2400 - start) + end) / 100;
    } else if(start < end) {
        diff = (end - start) / 100;
    } else {
        diff = 0;
    }

    return diff;

}

Functions are passed in as military time and it should return the amount of hours in between. 函数作为军事时间传递,它应返回两者之间的小时数。 Passed in values will always be "easy" numbers such as 1200, 1400, 2100 not 2134 or 015. It needs to be able to properly calculate all possible cases, will this function hold? 传递的值总是“简单”数字,例如1200,1400,2100而不是2134或015.它需要能够正确计算所有可能的情况,这个函数会保持吗?

I had trouble for values ranging from the night (8PM or 2000) to the next day (6AM or 600) and I think this should fix it? 我从晚上(晚上8点或2000年)到第二天(早上6点或600点)的价值观都遇到了麻烦,我认为应该解决这个问题?

Thanks for the time. 谢谢你的时间。

Just to be different, here's a version without any conditionals at all: 只是为了与众不同,这里是一个没有任何条件的版本:

private int calcHourDiff(int start, int end) {
    return ((end - start + 2400) % 2400) / 100;
}

Looks good. 看起来不错。

When comparing two numbers, x and y, there are only 3 possible outcomes: x == y, x < y, x > y 比较两个数字x和y时,只有3种可能的结果:x == y,x <y,x> y

Your if block covers all three, and the math for each condition looks good. 你的if块涵盖了所有三个,每个条件的数学看起来都很好。

Just would be worried about the assumption that the data passed will always be "easy" and correct. 只是担心传递的数据总是“容易”和正确的假设。

private int calcHourDiff(int start, int end) {

  int newEnd = (start > end)?end + 2400 : end;
  return (newEnd - start) / 100;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM