Checking Time in java

Asked

Viewed 814 times

2

Given a list of times ex.: String[] times = {"11:00", "12:00", "13:00"};

I want to take my current time and compare with the list which is the next hour, eg.: current time is 11:30, taken from the list "12:00".

  • example only of how I will receive the time(I will receive in string same).

  • 1

    That one Time is what? java.sql.Time?

  • I’m passing the string and parse for Time..

2 answers

3

If you are referring to class java.sql.Time, then just use the method valueOf(String):

String hora1 = "23:00";
Time n1 = Time.valueOf(hora1 + ":00");

String hora2 = "02:15";
Time n2 = Time.valueOf(hora2 + ":00");

if (n1.after(n2))...

If you are using the android.text.format.Time, then see the javadoc:

This class was deprecated in API level 22.
Use GregorianCalendar Instead.

What translating into Portuguese is:

This class has been depreciated in API level 22.
Use GregorianCalendar instead.

  • Well I do not know what is best to use but the valueOf would not solve, because 23:00 continues saying that it is after 2:15 am.

  • @Josinaldo, but 11:00 is after 2:15! It’s 8:00 and 45 minutes later.

  • I understand, so this won’t work for what I want.

1


To compare dates you must use Android Calendar.

Calendar horaComparar = Calendar.getInstance();
horaComparar.setTime(new SimpleDateFormat("h:mm").parse(horarios[0]));

Date horaAtual = new Date(System.currentTimeMillis());

if (horaComparar.getTime().compareTo(horaAtual) > 0 ){
   // hora é posterior a hora Atual.
}
  • The return value is 0 if both dates are equal.
  • The return value is greater than 0 if the date is later than the argument date.
  • The return value is less than 0 if date is earlier than the argument date.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.