user17864647
user17864647

Reputation: 310

SwiftUI: DatePicker/Date() formating

I have a .sheet element, that acts as a form when a user is adding to a calendar. Everything works as expected, but as soon as they submit, and upload the Date, Start Time, and end time into firebase where it's held, I noticed a problem. The date and time were formated weird.

My question is, how can I change the var scheduledate to a mm/dd/yy format when stored, and how can I change the var starttime and var endtime to a h:mm format when stored.

Here's my code:

struct SheetView: View {

var userEmail = Auth.auth().currentUser?.email
@Environment(\.dismiss) var dismiss
@State private var scheduledate = Date() //Store this as mm/dd/yy
@State private var startTime = Date() //Store this as h:mm
@State private var endTime = Date() //Store this as h:mm
@State private var scheduleairplane = ""
@State private var scheduleinstructor = ""

var body: some View {
    VStack {
        HStack {
            Text("New Flight")
                .font(.title)
                .fontWeight(.bold)
            Spacer()
            Button("Cancel") {
                dismiss()
            }
            
        }
        .padding()
        VStack {
            DatePicker("Date", selection: $scheduledate, displayedComponents: .date)
                .datePickerStyle(GraphicalDatePickerStyle())
                .frame(maxHeight: 400)
            DatePicker("Start Time", selection: $startTime, displayedComponents: .hourAndMinute)
                .datePickerStyle(GraphicalDatePickerStyle())
                .padding(.leading)
            DatePicker("End Time", selection: $endTime, displayedComponents: .hourAndMinute)
                .datePickerStyle(GraphicalDatePickerStyle())
                .padding(.leading)
        }
        VStack {
            TextField("Airplane...", text: self.$scheduleairplane)
                .padding([.leading, .trailing])
                .offset(x: 10)
                .frame(height: 30)
                .overlay(
                    RoundedRectangle(cornerRadius: 30)
                        .stroke(Color.white, lineWidth: 1)
                        .padding([.leading, .trailing])
                )
            TextField("Instructor...", text: self.$scheduleinstructor)
                .padding([.leading, .trailing])
                .offset(x: 10)
                .frame(height: 30)
                .overlay(
                    RoundedRectangle(cornerRadius: 30)
                        .stroke(Color.white, lineWidth: 1)
                        .padding([.leading, .trailing])
                )
        }
        
        Spacer(minLength: 0)
        Button(action: {
            let doc = db.collection("Scheduled").document("\(userEmail ?? "Error")")

            // Atomically add a new region to the "regions" array field.
            doc.updateData([
                "Airplanes": FieldValue.arrayUnion(["\(scheduleairplane)"])
            ])
            doc.updateData([
                "Date": FieldValue.arrayUnion(["\(scheduledate)"])
            ])
            doc.updateData([
                "Time": FieldValue.arrayUnion(["\(ScheduledTime)"])
            ])
            doc.updateData([
                "Instructor": FieldValue.arrayUnion(["\(scheduleinstructor)"])
            ])
        }) {
            Text("Submit")
        }
        .foregroundColor(.white)
        .frame(width: 120, height: 45)
        .background(Color("Blue"))
        .cornerRadius(30)
        .padding(.bottom)
         }
     }
 }

Upvotes: 0

Views: 4814

Answers (2)

user17864647
user17864647

Reputation: 310

Thanks for all the help but I found an answer here that works very well and is easy.

I used 3 different functions that I ran when I click the button. Then I send them off to firebase with the new values.

func updateDate() {
let selecteddate = scheduleddate //Here it gets the date and saves as another variable
let formatter1 = DateFormatter()
formatter1.dateStyle = .short
//I then made a saved string called newscheduledate to use this new variable anywhere in my project.
newscheduledate = formatter1.string(from: selecteddate) //Here is when it sets the conversion to a string which I used when I sent to firebase.
}

I then used this piece of code below twice, for the start time, and the end time.

func updateTime() {
let selectedtime = startTime //Here it gets the date
let formatter2 = DateFormatter()
formatter2.timeStyle = .medium
//I have a saved string called newstarttime to use this new variable anywhere in my project.
newstarttime = formatter2.string(from: selectedtime)
}

Upvotes: 1

Leo Chen
Leo Chen

Reputation: 340

class GeneralExtension{
    static func DateToStr(date:Date,format:String = "yyyy/MM/dd HH:mm:ss")->String{
        let timeFormatter = DateFormatter()
        timeFormatter.locale = Locale.current 
        timeFormatter.timeZone = TimeZone.current 
        timeFormatter.dateFormat = format
        let nowTimestr = timeFormatter.string(from: date)
        return nowTimestr
    }
    static func StrToDate(dateStr:String,format:String = "yyyy/MM/dd HH:mm:ss")->Date{
        var cbDate:Date = Date()
        if(!dateStr.isEmpty){
            let dateFormatter=DateFormatter()
            dateFormatter.dateFormat=format
            let tmpDate = dateFormatter.date(from: dateStr)
            if let tmpDate = tmpDate{
                cbDate = tmpDate
            }
        }
        return cbDate
    }   
}

example

GeneralExtension.DateToStr(date: dateSetting,format: "MM")

or

extension String{
    func StrToDate(format:String = "yyyy/MM/dd HH:mm:ss")->Date{
        var cbDate:Date = Date()
        if(!self.isEmpty){
            let dateFormatter=DateFormatter()
            dateFormatter.dateFormat=format
            let tmpDate = dateFormatter.date(from: self)
            if let tmpDate = tmpDate{
                cbDate = tmpDate
            }
        }
        return cbDate
    }
}

extension Date{
    func DateToStr(format:String = "yyyy/MM/dd HH:mm:ss")->String{
        let timeFormatter = DateFormatter()
        timeFormatter.locale = Locale.current
        timeFormatter.timeZone = TimeZone.current
        timeFormatter.dateFormat = format
        
        let nowTimestr = timeFormatter.string(from: self)
        return nowTimestr
    }
}

example

let date = Date()
let dateStr = date.DateToStr("MM")
let convertDate = dateStr.StrToDate()

Upvotes: 0

Related Questions