Skip to content

Instantly share code, notes, and snippets.

@waseefakhtar
Last active September 2, 2023 15:52
Show Gist options
  • Save waseefakhtar/1d73bb906613096b3ac31d4cc1b694a0 to your computer and use it in GitHub Desktop.
Save waseefakhtar/1d73bb906613096b3ac31d4cc1b694a0 to your computer and use it in GitHub Desktop.
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EndDateTextField(endDate: (Long) -> Unit) {
Text(
text = stringResource(id = R.string.end_date),
style = MaterialTheme.typography.bodyLarge
)
val interactionSource = remember { MutableInteractionSource() }
val isPressed: Boolean by interactionSource.collectIsPressedAsState()
val currentDate = Date().toFormattedString()
var selectedDate by rememberSaveable { mutableStateOf(currentDate) }
val context = LocalContext.current
val calendar = Calendar.getInstance()
val year: Int = calendar.get(Calendar.YEAR)
val month: Int = calendar.get(Calendar.MONTH)
val day: Int = calendar.get(Calendar.DAY_OF_MONTH)
calendar.time = Date()
val datePickerDialog =
DatePickerDialog(context, { _: DatePicker, year: Int, month: Int, dayOfMonth: Int ->
val newDate = Calendar.getInstance()
newDate.set(year, month, dayOfMonth)
selectedDate = "${month.toMonthName()} $dayOfMonth, $year"
endDate(newDate.timeInMillis)
}, year, month, day)
TextField(
modifier = Modifier.fillMaxWidth(),
readOnly = true,
value = selectedDate,
onValueChange = {},
trailingIcon = { Icons.Default.DateRange },
interactionSource = interactionSource
)
if (isPressed) {
datePickerDialog.show()
}
}
fun Int.toMonthName(): String {
return DateFormatSymbols().months[this]
}
fun Date.toFormattedString(): String {
val simpleDateFormat = SimpleDateFormat("LLLL dd, yyyy", Locale.getDefault())
return simpleDateFormat.format(this)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment