如何检查一天中的时间是否在两次之间? [英] How to check if time in day is between two times?

查看:70
本文介绍了如何检查一天中的时间是否在两次之间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我创建了一个代表高中班级的对象。此对象包含2个日历对象,分别代表班级每天的开始和结束时间。当用户创建作业时,我要检查当前时间是否在任何课程的两次之间。如果是的话,我知道作业是在该课程中创建的。这是我当前无法使用的代码,因为.getTime()返回一个包含月和日的日期,而我只想比较小时和分钟。因此,如何修剪返回的日期,使其仅包含一天中的时间?使用joda-time会更容易吗?如果可以,应该使用什么类?

In my app I create an object that represents a high school class. This object holds 2 Calendar objects that represents the class's start and stop time each day. When a user creates an assignment I want to check if the current time is between the two times of any of the classes. If it is I know that the assignment was created during that class. Here is my current code that does not work because .getTime() returns a date that includes month, and day, while I would just like to compare hours, and minutes. SO how can I trim the returned dates to just include the time in day? Would this be easier with joda-time, and if so what classes should be used?

    public void checkTimeFrame() {
    time = Calendar.getInstance().getTime();
    ArrayList<SchoolClass> mList = mClassList;

    // Changes index if assignment falls under time frame of class
    for (int a = 0; a < mList.size(); a++) {
        if (mList.get(a).getStartTime() != null && mList.get(a).getEndTime() != null &&
                time.after(mList.get(a).getStartTime().getTime()) && time.before(mList.get(a)
                .getEndTime().getTime())) {
            index = a;
            updateClassEditText();
        }
    }
}


推荐答案

您可以使用 Calendar.get(),如另一个答案所述。不过,要比较分钟,您应该使用 Calendar.MINUTE 也是如此:

You can use Calendar.get(), as mentioned in another answer. To compare minutes, though, you should use Calendar.MINUTE, too:

int minutes_in_day = time.get(Calendar.HOUR_OF_DAY)*60 + time.get(Calendar.MINUTE);

然后,您可以将当前时间当天的分钟数与开始时间进行比较,然后结束时间。当然,只有在同一时间,这才起作用。

Then, you can just compare the minutes within the day of the current time with that of the start and end times. This will, of course, only work when the times are in the same day.

这篇关于如何检查一天中的时间是否在两次之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆