Reputation: 2809
I have a UIDatePicker which displays the date using the Islamic Calendar. The datePicker is displaying the values in the correct format. However, when I assign the users selection to the UITextField, it unfortunately displays the equivalent date in Gregorian calendar format. How can I change this so that it displays the Islamic calendar equivalent?
Here is the relevant code:
//The below code is what displays the dates from the Islamic calendar in the UIDatePicker (and works correctly):
let islamicCalendar = NSCalendar.init(calendarIdentifier: NSCalendarIdentifierIslamic)
let components: NSDateComponents = NSDateComponents()
components.calendar = islamicCalendar
components.year = 10
let currentDate = NSDate()
let maxDate: NSDate = islamicCalendar!.dateByAddingComponents(components, toDate: currentDate, options: [])!
self.datePicker?.calendar = islamicCalendar
self.datePicker?.minimumDate = NSDate()
self.datePicker?.maximumDate = maxDate
This is the block of code which converts the users selection and assigns it to the appropriate UITextField:
var selectedDate: String = String()
selectedDate = self.dateformatterDateTime(self.datePicker!.date) as String
myTextField.text = selectedDate
func dateformatterDateTime(date: NSDate) -> NSString {
let dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
return dateFormatter.stringFromDate(date)
}
Upvotes: 0
Views: 713
Reputation: 3361
try this,
let picker = UIDatePicker(frame: CGRect(x: 0, y: 30, width: 0, height: 0))
picker.datePickerMode = .date
picker.date = Date()
picker.calendar = Calendar(identifier: .islamicUmmAlQura)
picker.autoresizingMask = UIViewAutoresizing.flexibleRightMargin
picker.frame.size.width = 300
view.addSubview(picker)
Upvotes: 0
Reputation: 5659
You should either convert the selected date into islamic date in your func dateformatterDateTime(date: NSDate) -> NSString
method or send this method a converted date. You can do it so by -
var selectedDate: String = String()
var date = (islamicCalendar?.date(byAdding:components, to: self.datePicker!.date, options: []))!
selectedDate = self.dateformatterDateTime(date) as String
myTextField.text = selectedDate
func dateformatterDateTime(date: NSDate) -> NSString {
let dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
return dateFormatter.stringFromDate(date)
}
or -
func dateformatterDateTime(date: Date) -> NSString {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
var dateToSendBack = (islamicCalendar?.date(byAdding:components, to: date, options: []))!
return dateFormatter.string(from: dateToSendBack)
}
Upvotes: 1