gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 00:48:51 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com