1

I'm trying to make a if-else statement that if user put time which have past, it will alert the user that the time has past. And I also unable to set the timedialogpicker to the current time when the user open it. Thanks in advance.

The code:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Calendar timeNow = Calendar.getInstance();
        timePickerDialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                int currHour = calendar.get(Calendar.HOUR_OF_DAY);
                int currMin = calendar.get(Calendar.MINUTE);
                Time currTime = new Time(currHour, currMin); //This part display error
                if (currTime.getTimeInMillis() >= timeNow.getTimeInMillis()) { //This part display error
                    //it's after current
                    int hour = hourOfDay % 12;
                } else {
                    //it's before current'
                    Toast.makeText(getApplicationContext(), "Invalid Time", Toast.LENGTH_LONG).show();
                }
                time = "";
                time = hourOfDay+":"+minute;

                Userbook book = new Userbook(temp, time);

                db.collection("Booking").add(book).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {
                        Toast.makeText(MainActivity.this, "Note saved", Toast.LENGTH_SHORT).show();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
                    }
                });
               Toast.makeText(MainActivity.this, "Time is "+currHour+":"+currMin, Toast.LENGTH_SHORT).show();
            }
        },timeNow.get(Calendar.HOUR_OF_DAY), timeNow.get(Calendar.MINUTE),false);
        timePickerDialog.show();
    }
});
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 1
    Assuming `java.sql.Time` I strongly recommend you don’t use that class here, Also consider not using `Calendar`. Both classes are poorly designed and long outdated. Use [desugaring](https://developer.android.com/studio/write/java8-support-table) in order to use [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). It is so much nicer to work with. You want [the `LocalTime` class](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalTime.html) and its `isBefore` or its `isAfter` method and possibly other classes. – Ole V.V. Nov 28 '22 at 20:40

2 Answers2

4

In brief: ! LocalTime.of( 10 , 20 ).isBefore( LocalTime.now() )

! LocalTime#isBefore

The java.time API, released with Java-8 in March 2014, supplanted the error-prone legacy date-time API. Since then, it has been strongly recommended to use this modern date-time API.

You can use LocalTime#of(int hour, int minute) to get an instance of LocalTime with the given hour and minute values and then compare it with the current time (i.e. LocalTime#now) using LocalTime#isBefore.

Demo:

import java.time.LocalTime;

public class Main {
    public static void main(String[] args) {
        LocalTime now = LocalTime.now();

        // Sample hour and minute values
        int hour = 10;
        int minute = 20;

        LocalTime givenTime = LocalTime.of(hour, minute);

        System.out.println(!givenTime.isBefore(now));
    }
}

Output:

false

!givenTime.isBefore(now) means givenTime is either equal to or after now.

Learn more about the modern Date-Time API from Trail: Date Time.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 1
    I think I manage to solve the current time because I'm using the wrong time zone for my app. I will be sure to use the modern API for my app. – Haziq Mt Roslan Nov 29 '22 at 03:18
1

One way to approach this is to set the calendar's time to new Date(), and then set the hours and minutes to the selected values. e.g,

Then you can use Java's built compareTo function to compare the two dates. eg:

        Calendar timeNow = Calendar.getInstance();
        Date curDate = new Date();
        timeNow.setTime(curDate);
        timeNow.set(Calendar.HOUR_OF_DAY, hourOfDay);
        timeNow.set(Calendar.MINUTE, minute);
        // If you want to warn on dates being equal to current time, then 
        // switch the conditional to be greater than or equal to 0, instead
        // of greater than 0. 
        if (curDate.compareTo(timeNow.getTime()) > 0) {
           //it's after current
           int hour = hourOfDay % 12;
        }
        ...
        ...
Devin Sag
  • 79
  • 5
  • 2
    You are using terrible date-time classes that were years ago supplanted by the *java.time* classes defined in JSR 310. See modern solution in Answer by [Arvind Kumar Avinash](https://stackoverflow.com/a/74606418/642706). – Basil Bourque Nov 28 '22 at 22:03
  • Yup. I was following old Youtube video to learn these functionality. Thanks for the advice. – Haziq Mt Roslan Nov 29 '22 at 03:18