0

i want to compare two time (hour and minute) in textView. I try to convert there into millisecond, but it looks does'n work. Or maybe you have other way to covert . .

String startTime = (String) tvDisplayTime.getText(); 
String endTime = (String) tvDisplayTime.getText();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");   

    try {
        Date StartDate = sdf.parse(startTime);
        long timeInMillisecondsStart = StartDate.getTime();

        Date EndDate = sdf.parse(endTime);
        long timeInMillisecondsEnd = Enddate.getTime();

        long result = timeInMillisecondsEnd-timeInMillisecondsStart;

            if (result > 0){
                Toast.makeText(MainActivity.this, " Work ", Toast.LENGTH_LONG).show();                          

            }else{
                    Toast.makeText(MainActivity.this, " Failed ", Toast.LENGTH_LONG).show();

                }
            } catch (ParseException e) {
                        e.printStackTrace();
            }
virho
  • 149
  • 2
  • 2
  • 9

3 Answers3

0

mate check your code :

String startTime = (String) tvDisplayTime.getText(); 
String endTime = (String) tvDisplayTime.getText(); 

your getting the same text all the time ...

endTime and startTime are always equal.

Itzik Samara
  • 2,278
  • 1
  • 14
  • 18
  • i try to use `after`, but not working. Result always failed. `if (EndDate.after(StartDate)){ work } else{failed}` – virho Jul 28 '14 at 11:42
0

There is no need to convert to a time in milliseconds. Just use the compareTo method on your date objects.

From the docs...

Returns:
an int < 0 if this Date is less than the specified Date, 0 if they are equal, and an int > 0 if this Date is greater.

Sound Conception
  • 5,263
  • 5
  • 30
  • 47
0

Your method works if you enter the time in the specified format /e.g. HH:mm/, but this can be quite frustrating for the user. Why not use TimePicker instead. There in the onTimeSet callback you get the time set by the user in int variables

public void onTimeSet(TimePicker view, int hourOfDay, int minute)

Example here: http://developer.android.com/guide/topics/ui/controls/pickers.html