xcodeswiftdatepickeruidatepicker

Displaying the Day Of The Week From Date Picker


I want to store just the day of the week as a string using a datePicker in xcode using swift.


Solution

  • import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var datePicker: UIDatePicker!
        @IBOutlet weak var strWeekday: UILabel!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // set mode to date only
            datePicker.datePickerMode = .date
    
            // add target for the trigger update function to change the weekday when the user changes the date
            datePicker.addTarget(self, action: #selector(triggerUpdate), for: .valueChanged)
    
            // weekday initial value
            strWeekday.text = datePicker.date.weekdayNameStandalone
        }
    
        @IBAction func triggerUpdate(_ datePicker: UIDatePicker) {
            strWeekday.text = datePicker.date.weekdayNameStandalone
        }
    }
    

    extension Date {
    
        // returns weekday name (Sunday-Saturday Localized) as String
        var weekdayNameStandalone: String {
            Formatter.weekdayNameStandalone.string(from: self)
        }
    
        // returns weekday name (Sunday-Saturday fixed locale en_US_POSIX) as String
        var weekdayNameStandAlonePosix: String {
            Formatter.weekdayNameStandAlonePosix.string(from: self)
        }
    
    }
    

    extension Formatter {
    
        static let weekdayNameStandalone: DateFormatter = {
            let formatter = DateFormatter()
            formatter.locale = .autoupdatingCurrent
            formatter.dateFormat = "cccc"
            return formatter
        }()
    
        static let weekdayNameStandAlonePosix: DateFormatter = {
            let formatter = DateFormatter()
            formatter.locale = .init(identifier: "en_US_POSIX")
            formatter.dateFormat = "cccc"
            return formatter
        }()
    }