我想创建一个将日期转换成文本格式,如“刚才,2分钟,1小时,1天,10月10日”的功能。这里就是我在得到一个错误,我的示例代码:如何将日期“MM-dd-yyyy hh:mm:ss a”转换为文字格式?
let components = cal.components([.Day,.Hour,.Minute], fromDate: date, toDate: NSDate(), options:[])
这里是我的全码:
func getTextToDisplayFormattingDate(date: NSDate) -> String {
var textToDisplay = ""
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy hh:mm:ss a"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let cal = NSCalendar.current
let components = cal.components([.Day,.Hour,.Minute], fromDate: date, toDate: NSDate(), options:[])
switch components.day {
case 0:
if components.hour == 0 {
if components.minute <= 0 {
textToDisplay = "just now "
} else {
textToDisplay = "\(components.minute) min"
}
} else {
textToDisplay = "\(components.hours) hrs"
}
case 1...6:
textToDisplay = "\(components.day) d"
default:
dateFormatter.dateFormat = "MMM dd"
textToDisplay = dateFormatter.string(from: date as Date)
}
return textToDisplay
}
从你的斯威夫特3码摆脱所有的斯威夫特2语法的。 – rmaddy