0

How to get input as a time from EditText in Android?

I want to get time from EditText and want to use that time in handler.

Example:

"00:00:03" needs to be converted to "3000" milliseconds.

Any idea?

Tom Taylor
  • 3,344
  • 2
  • 38
  • 63
  • does this answer your question, in whole or in part? [Java 8 Time API: how to parse string of format “mm:ss” to Duration?](https://stackoverflow.com/questions/24642495/java-8-time-api-how-to-parse-string-of-format-mmss-to-duration) – Ole V.V. Jul 04 '21 at 17:38

3 Answers3

0

If I understand you need to convert string (From edit text) to time in millisecond.

public static void main(String[] args) {
        String st="00:01:03";   
        LocalTime t = LocalTime.parse( st ) ;
        System.out.println(t);
        System.out.println(t.toSecondOfDay()*1000);
    }
Majid Hajibaba
  • 3,105
  • 6
  • 23
  • 55
  • `LocalTime` is for a time of day (or in this case: a time of the night). I suspect that the asker is rather dealing with an amount of time. If so, `LocalTime` is not the right class to use. – Ole V.V. Jul 04 '21 at 17:35
0

Get the value from your EditText

EditText txt = findViewById(R.id.edit);
String time = txt.getText().toString();

Then use LocalTime class from Java

LocalTime localTime = LocalTime.parse(time);
int millis = localTime.toSecondOfDay() * 1000; //Time in milliseconds
  • `LocalTime` is for a time of day (or in this case: a time of the night). I suspect that the asker is rather dealing with an amount of time. If so, `LocalTime` is not the right class to use. – Ole V.V. Jul 04 '21 at 17:35
0

If it's always going to be in HH:mm:ss format as per your example, you can do something like:

    val time = etTime.text.toString()
    val units = time.split(":")  // will split the string to array of 3 elements
    val hours = units[0].toInt()  // 1st element
    val minutes = units[1].toInt()  // 2nd element
    val seconds = units[2].toInt()  // 3rd element
    val totalTimeInMillis =
        ((hours * 3600) + (minutes * 60) + seconds) * 1000  // converting each unit to seconds and total sum to millis

This should do it. If your time is going to be in a different format for different cases, handle it accordingly. If it's too dynamic, handle it with something like SimpleDateFormat to always get the time in a certain format, and then you can again use the same logic. You can also define this as a helper method and reuse it at multiple places, returning millis from a given time format.

Yash Joshi
  • 557
  • 7
  • 25