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?
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?
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);
}
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
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.