Android - 检查时间是否在一天中的特定时间之间 [英] Android - checking if time is between certain hours of the day
问题描述
在我的应用程序中,如果时间介于用户选择的一天中的特定时间之间,我将更新一些内容.如果用户选择像07-21"这样的东西,它工作正常,但不是21-07",这是过夜.我如何检查时间是获取当前小时并将其转换为毫秒.然后我检查当前的毫秒数是否在所选的小时数之间(那些也被转换为毫秒).像这样:
in my app I'm updating some stuff if the time is between certain hours of the day which the user choose. It works fine if the user chooses something like "07-21", but not with "21-07" which is over the night. How I'm doing to check the time is I'm getting the current hour and converting it into milliseconds. Then I check if the current milli is between the chosen hours (those are also converted into milliseconds). Like this:
if (currentMilli >= startHourMilli && currentMilli <= endHourMilli)
问题:如果用户选择超过午夜(例如 19-08)的任何内容,则不起作用.
The problem: It doesn't work if the user chooses anything that is over midnight (19-08 for example).
我尝试了很多东西,但我就是不知道如何做到这一点.
I've tried a lot of stuff but I just can't figure out how to do this.
感谢任何帮助!
推荐答案
当你过了午夜时,你是否将一年中的一天加 1?否则你的startHourMilli
可能大于 endHourMilli
并且您的 if 子句将始终为 false.
Do you increase the day of the year by 1 when you're passing midnight? Otherwise your
startHourMilli
might be greater than endHourMilli
and your if-clause will always be false.
解决办法是使用Calendar类的add-method
.因此,我以小时为单位计算间隔的长度,并将此值添加到我们的 Calendar 实例中.
The solution is to use the add-method
of the Calendar class. Therefore I calculate the interval's length in hours and add this value to our Calendar instance.
int start = 21; // let's take your failing example: 21-07
int end = 7;
int hours = (end - start) % 24; // here hours will be 14
Calendar cal = Calendar.getInstance();
// set calendar to TODAY 21:00:00.000
cal.set(Calendar.HOUR_OF_DAY, start);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long startHourMilli = cal.getTimeInMillis();
// add 14 hours = TOMORROW 07:00:00.000
cal.add(Calendar.HOUR_OF_DAY, hours);
long endHourMilli = cal.getTimeInMillis();
让我知道这是否有帮助:)
Let me know if this helps :)
这篇关于Android - 检查时间是否在一天中的特定时间之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!