How to compare current time with time range?

前端 未结 8 1733
庸人自扰
庸人自扰 2020-12-30 12:02

I have two String variables - time1 and time2. Both contain value in the format HH:MM. How can I check:

  1. If the current time
相关标签:
8条回答
  • 2020-12-30 12:31

    Look into the Calendar class. It has the methods to support what you are asking. Date is deprecated and not recommended to use.

    Here is the link to the API. Calendar

    About the usage. First you need to call Calendar.getInstance() to create a calendar object. Next you need to Set the two fields using cal.set(Calendar.HOUR, your hours) and Calendar.MINUTES the same way. Next you can call the compare function, before or after functions to get the desired info. Also you can get an instance with the current time in the current locale.

    0 讨论(0)
  • 2020-12-30 12:38

    This is what I used as simple function and it worked for me:

    public static boolean isTimeWith_in_Interval(String valueToCheck, String startTime, String endTime) {
        boolean isBetween = false;
        try {
            Date time1 = new SimpleDateFormat("HH:mm:ss").parse(startTime);
    
            Date time2 = new SimpleDateFormat("HH:mm:ss").parse(endTime);
    
            Date d = new SimpleDateFormat("HH:mm:ss").parse(valueToCheck);
    
            if (time1.before(d) && time2.after(d)) {
                isBetween = true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return isBetween;
    }
    
    0 讨论(0)
提交回复
热议问题