从Swift中的UIDatePicker中选择时,无法以正确的格式显示日历

时间:2016-07-14 05:39:26

标签: ios swift nscalendar

我有一个UIDatePicker,它使用伊斯兰日历显示日期。 datePicker以正确的格式显示值。但是,当我将用户选择分配给UITextField时,遗憾的是它以格里高利历显示格式显示等效日期。如何更改此设置以显示等效的伊斯兰日历?

以下是相关代码:

//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

这是转换用户选择并将其分配给相应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)

 }

2 个答案:

答案 0 :(得分:1)

您应该在func dateformatterDateTime(date: NSDate) -> NSString方法中将所选日期转换为伊斯兰日期,或者将此方法转换为转换日期。你可以通过 -

这样做
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)
}

或 -

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)
}

答案 1 :(得分:0)

试试这个,

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)