Home > Blockchain >  How to change timezone of DatePicker in SwiftUI
How to change timezone of DatePicker in SwiftUI

Time:01-31

I'm trying to make an mobile app for a reservation system. Users can reserve the product from different timezones. So when a user from NY city tries to reserve a product from Paris, I need to be sure user selected the time in Europe/Paris timezone. Currently swiftUI datepicker uses the system current timezone which is of course GMT-5 so when they select 13:00 the Date() object sets itself to 18:00 UTC, but I need him/her to be select in GMT 1 so when they select 13:00 I should set the Date() object to 12:00 UTC. I have tried to use environment value for timezone but it changes the timezone application wide, I just need to change the timezone of datepicker not all application. Here are the solutions I've tried to change timezone

DatePicker("", selection: $viewModel.tripRequest.date, displayedComponents: .hourAndMinute)
                    .labelsHidden()
                    .padding(.horizontal)
                    .font(.custom("Gilroy-Regular", size: 36))
                    .cornerRadius(15)
                    .environment(\.timeZone, TimeZone(secondsFromGMT: 3600)!)

I've also tried to use introspect with no luck

DatePicker("", selection: $viewModel.tripRequest.date, displayedComponents: .hourAndMinute)
                    .labelsHidden()
                    .padding(.horizontal)
                    .font(.custom("Gilroy-Regular", size: 36))
                    .cornerRadius(15)
                    .introspectDatePicker { datePicker in
                        datePicker.timeZone = TimeZone(secondsFromGMT: 3600)
                    }

CodePudding user response:

SwiftUI's DatePicker uses the device's Timezone by default.

You can specify a Timezone using .environment(\.timeZone, TimeZone(identifier: "Specific identifier")!)

But Date is in UTC so if the user picks a date in one timezone when viewed in another timezone it will be adjusted. You can't change the timezone for Date.

import SwiftUI

struct WorldTimeView: View {
    @State private var date: Date = .init()
    var body: some View {
        VStack{
            
            DatePicker("US", selection: $date, displayedComponents: .hourAndMinute)
            //US Date Picker
                .environment(\.timeZone, TimeZone(identifier: "America/New_York")!)
           
            
            DatePicker("Paris", selection: $date, displayedComponents: .hourAndMinute)
            //Paris Date Picker
                .environment(\.timeZone, TimeZone(abbreviation: "CET")!)
            
            //User/Device Date Picker
            DatePicker("Local", selection: $date, displayedComponents: .hourAndMinute)
        }
    }
}

struct WorldTimeView_Previews: PreviewProvider {
    static var previews: some View {
        WorldTimeView()
    }
}

enter image description here

  • Related