here is a simple timePickerUtil:
class TimePickerHelper(
val context: Context,
private val inputTime: String,
val callback: (time: String) -> Unit
) {
fun showPicker() {
var hour = 0
var minute = 0
val formattedInputTime = covertDate(
inputTime,
Constants.DateFormats.HH_MM_A,
Constants.DateFormats.HH_MM
)
if (formattedInputTime.isNotEmpty()) {
val arr = formattedInputTime.split(":")
hour = arr[0].toInt()
minute = arr[1].toInt()
}
val timePickerDialog = TimePickerDialog(
context,
{ view, h, m ->
callback(
covertDate(
"$h:$m",
Constants.DateFormats.HH_MM,
Constants.DateFormats.HH_MM_A
)
)
},
hour,
minute,
false
)
timePickerDialog.show()
}
}
@SuppressLint("SimpleDateFormat")
fun covertDate(date: String, inputFormat: String, outputFormat: String): String {
var formattedDate = ""
try {
val dateObject =
SimpleDateFormat(inputFormat).parse(date)
formattedDate = SimpleDateFormat(outputFormat).format(dateObject)
} catch (e: Exception) {
Timber.e(e)
}
return formattedDate
}
//Belongs to Constants class
object DateFormats {
const val TIME_STAMP_WITH_ZONE: String = "yyyy-MM-dd'T'HH:mm:ss.s"
const val MMM_YYYY: String = "MMM YYYY"
const val DD_MM_YY: String = "dd/MM/yy"
const val HH_MM_A: String = "hh:mm aa"
const val HH_MM: String = "HH:mm"
}