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

标签 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)

 }

最佳答案

您应该在 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)
}

关于ios - 从 Swift 中的 UIDatePicker 中选择时无法以正确格式显示日历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38366236/

相关文章:

ios - 将流媒体视频(m3u8 文件)保存到图库中

ios - Xcode UI 测试允许系统警报系列

iphone - UIToolBar 不绘制在 iPhone 屏幕底部

ios - 无法正确自动调整自动布局和堆栈 View (Swift 3、Xcode 8)

ios - NSCalendar 的 dateBySettingUnit 方法返回不明显的结果

ios - 查明两个日期之间是否已经过去了两个日历日

ios - 表格 View 单元格中的 Storyboard ImageView

swift - 带有 TableView 的 EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)

ios - 无法在 Swift 3/Xcode 8.2.1 中导入 EventKit

ios - Cocoa Touch日历类中缺少枚举?