I'm trying to create a simple app where the user needs to select a date. My issue is that it defaults to the date according to UTC time unless I add in the zone off set. My confusion is that I thought that val currentZonedDateTime = ZonedDateTime.now(ZoneId.systemDefault()) would account for the time zone. I find my self having to add in the offset. Other wise after 6:00PM it defaults to the next day.

val currentZonedDateTime = ZonedDateTime.now(ZoneId.systemDefault())
val zoneOffset = currentZonedDateTime.offset
val datePickerState = rememberDatePickerState(
initialSelectedDateMillis = currentZonedDateTime.toInstant().toEpochMilli(),
//initialSelectedDateMillis = currentZonedDateTime.toInstant().toEpochMilli() + zoneOffset.totalSeconds * 1000,)
If I use the debugger it shows currentZonedDateTime set to America/Chicago. So why does it show UTC time unless I add in the code to add the zoneOffSet? Is there a better way to do this? It works if I add in the commented code. I'm confused why I need to.

So why does it show UTC time unless I add in the code to add the zoneOffSet?
Because you convert your currentZonedDateTime into an Instance via currentZonedDateTime.toInstant().toEpochMilli() and an Instance "is as a single moment in time in the UTC time zone". You basically converted your timestamp back into UTC time.
Is there a better way to do this?
If by better you mean a way without adding the offset manually I don't think so. I would be happy to be corrected on this but so far I haven't found a method that gives you the milliseconds since epoch with the timezone included. I assume that you want to show the date in your users timezone and since the DatePicker uses UTC (and more so at the start of the day of that day 00:00!) you need to adjust for that. I would recommend storing everything as UTC and then when you need to present the timestamp to the user, be it as a readable string or in this case via a DatePicker dialog, to format it accordingly.
The funny thing is, the TimePicker seems to display the time adjusted to your local time, e.g. if you feed it a UTC timestamp you will see your current local time and not UTC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With