Search code examples
androidalarmmanagerdatetimepickerandroid-jobscheduler

Two TimePickers comparison


So I have allowed the user to pick two Dates Start and End time and connected to Notification Method that will check if the Current time is between his choosing. However the comparison doesn't seem to return the correct result. Here are the method inside the BrodcatRecevier:

    public void CheackAlarmAllow(){
    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
    FinalTime = Calendar.getInstance();
    FinalTime.get(Calendar.HOUR);
    FinalTime.get(Calendar.MINUTE);
    FinalTime.get(Calendar.SECOND);
    FinalTimeS = dateFormat.format (FinalTime.getTime());


    DatabaseHelper db = new DatabaseHelper(this);
    ProfileHelper response = db.getNotification();

    try {
        FirstTime = dateFormat.parse (response.StartTimePicker);
        SecondTime = dateFormat.parse (response.EndimePicker);
        FinalTimeD = dateFormat.parse (FinalTimeS);


    }catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    if(FinalTimeD.after(FirstTime)&& FinalTime.before(SecondTime))
    {
        Log.w("Not Allowed","Working");
    }
    else
    {
        Log.w("FirstTime", String.valueOf(FirstTime));
        Log.w("Second", String.valueOf(SecondTime));
        Log.w("Final", String.valueOf(FinalTimeD));
        Log.w(" Allowed","Working");
        createNotification();
    }
}

And Here the Log returns.

06-03 08:14:10.597 30078-7708/com.ahmad.Project W/FirstTime: Thu Jan 01 
03:00:00 MST 1970

06-03 08:14:10.598 30078-7708/com.ahmad. Project W/Second: Thu Jan 01 
10:00:00 MST 1970

06-03 08:14:10.598 30078-7708/com.ahmad. Project W/Final: Thu Jan 01 
08:14:00 MST 1970

06-03 08:14:10.598 30078-7708/com.ahmad. Project W/ Allowed: Working

Solution

  • Your if check if(FinalTimeD.after(FirstTime)&& FinalTime.before(SecondTime)) fails because FirstTime and SeconfTime are of type Date and Calendar.after() returns true only if the param passed is of type Calendar
    From the Oracle documentation of Calender.after():-

    public boolean after(Object when) Returns whether this Calendar represents a time after the time represented by the specified Object. This method is equivalent to:
    compareTo(when) > 0 if and only if when is a Calendar instance. Otherwise, the method returns false.

    EDIT (Copying code snippet from comments below for completeness)

    Calendar calendar = Calendar.getInstance(); 
    Date newDate = calendar.setTime(date);