andrewphiri / Date_Dialogs_Sample

Sample project showing how to use date picker in jetpack compose
1 stars 0 forks source link

Date Selected is off by one day #1

Open srseibs opened 3 weeks ago

srseibs commented 3 weeks ago

I think there is an error related to time zones. I am located in California and it is presently 5:46 PM Pacific Daylight Time (GMT - 7). The date picker calendar shows I selected Sep 03, but the TextView shows the value to be Sep 02.

I had a similar problem with my own app, saw your Medium article with a sample, and was hoping it would work better than mine.

2024-09-23_17-46-12

andrewphiri commented 3 weeks ago

@RequiresApi(Build.VERSION_CODES.O) fun convertMillisToLocalDate(millis: Long): ZonedDateTime { // Interpret the milliseconds as the start of the day in UTC, then convert to localdate val utcDateAtStartOfDay = Instant .ofEpochMilli(millis) .atZone(ZoneOffset.UTC) .toLocalDate() println("UTC Date at Start of Day: $utcDateAtStartOfDay") // Debugging UTC date // Convert to the same instant in Local time zone val localDate = utcDateAtStartOfDay.atStartOfDay(ZoneId.systemDefault()) println("Local Date: $localDate") // Debugging local date return localDate } 1 . I am converting the Instant to ZonedDateTime at UTC time zone and then getting only the date portion by converting it to local date.

  1. Then I convert that date to a local ZonedDateTime by setting the time to midnight in the local time zone (e.g., "America/Los_Angeles" if that’s your system’s default). Let me know if it works.
srseibs commented 3 weeks ago

That seems to work! Thanks.