How to compare current time with time range?

前端 未结 8 1748
庸人自扰
庸人自扰 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:23

    • Convert the two strings to Date objects (which are also time objects) Create a new Date object.
    • This will contain the current time.
    • Use the Date.before() and Date.after() methods to determine if you are in the time interval.

    EDIT: You should be able to use this directly (and no deprecated methods)

    public static final String inputFormat = "HH:mm";
    
    private Date date;
    private Date dateCompareOne;
    private Date dateCompareTwo;
    
    private String compareStringOne = "9:45";
    private String compareStringTwo = "1:45";
    
    SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
    
    private void compareDates(){
        Calendar now = Calendar.getInstance();
    
        int hour = now.get(Calendar.HOUR);
        int minute = now.get(Calendar.MINUTE);
    
        date = parseDate(hour + ":" + minute);
        dateCompareOne = parseDate(compareStringOne);
        dateCompareTwo = parseDate(compareStringTwo);
    
        if ( dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
            //yada yada
        }
    }
    
    private Date parseDate(String date) {
    
        try {
            return inputParser.parse(date);
        } catch (java.text.ParseException e) {
            return new Date(0);
        }
    }
    

提交回复
热议问题