iosswiftuidatepickerxcode16

How can i Adding hours to a selected hour in SwiftUI to transform local hours in to Zulu hours


Does anyone can help me or point me in the right direction in order to adding hours to get Zulu hours from a selected time for example i have this peace of code:

struct datepicker: View {
    @State var startTime: Date = .now
    @State var zuluTime = ""
    var body: some View {
        VStack {
            DatePicker("_", selection: $startTime, displayedComponents: .hourAndMinute)
                .labelsHidden()
          Text(zuluTime)
        }
        .environment(\.locale, .init(identifier: "da"))
    }
}

This code gives the time in 24 format but i want to display also the Zulu time for example if you have 19:00 the zulu times adds or substract hours depending on your time zone if your at UTC + 5 you have to add 5 hours to the time 19:00 - > 00:00 (of next day) thanks in advance for any help or tip


Solution

  • Try this approach using a DateFormatter, such as:

    struct ContentView: View {
        @State private var startTime: Date = .now
        
        var formatter: DateFormatter {
            let frmt = DateFormatter()
            frmt.dateFormat = "MMMM dd, yyyy 'at' hh:mm"
            frmt.locale = Locale(identifier: "da")
            frmt.timeZone = TimeZone(abbreviation: "UTC") // zulu (UTC) time
            return frmt
        }
        
        var body: some View {
            VStack {
                DatePicker("_", selection: $startTime, displayedComponents: .hourAndMinute)
                    .labelsHidden()
                    .datePickerStyle(.wheel)
                Text(formatter.string(from: startTime)) // zulu (UTC) time
            }
            .environment(\.locale, .init(identifier: "da"))
        }
    }
    

    Or this:

    struct ContentView: View {
        @State private var startTime: Date = .now
        @State private var zuluTime = ""
        
        var formatter: DateFormatter {
            let frmt = DateFormatter()
            frmt.dateFormat = "hh:mm"
            frmt.locale = Locale(identifier: "da")
            frmt.timeZone = TimeZone(abbreviation: "UTC") // zulu (UTC) time
            return frmt
        }
        
        var body: some View {
            VStack {
                DatePicker("_", selection: $startTime, displayedComponents: .hourAndMinute)
                    .labelsHidden()
                    .datePickerStyle(.wheel)
                Text(zuluTime) // zulu (UTC) time
                Text(startTime, style: .time) // local time
            }
            .environment(\.locale, .init(identifier: "da"))
            .onChange(of: startTime) {
                zuluTime = formatter.string(from: startTime)
            }
            .onAppear {
                zuluTime = formatter.string(from: startTime)
            }
        }
    }