我正在尝试创建一个将日期转换为文本格式的函数,例如“刚刚,2 分钟,1 小时,1 天,10 月 10 日”。这是我在以下位置遇到错误的示例代码:
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
}
最佳答案
像这样使用:
我的代码中的更改:
- 代替
NSDate
,我使用了Date
。 - 代替
NSCalendar
我使用Calendar
components(_:from:to:options:)
已重命名为dateComponents(_:from:to:)
components
值,例如day, minute, hour
是optional
。这就是我在切换前添加检查的原因。func getTextToDisplayFormattingDate(date: Date) -> String { var textToDisplay = "" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM-dd-yyyy hh:mm:ss a" dateFormatter.timeZone = TimeZone(identifier: "UTC") let cal = Calendar.current let components = cal.dateComponents([.day, .hour , .minute], from: date, to: Date()) if let day = components.day, let minute = components.minute, let hour = components.hour { switch day { case 0: if hour == 0 { if minute <= 0 { textToDisplay = "just now " } else { textToDisplay = "\(minute) min" } } else { textToDisplay = "\(hour) hrs" } case 1...6: textToDisplay = "\(day) d" default: dateFormatter.dateFormat = "MMM dd" textToDisplay = dateFormatter.string(from: date) } } return textToDisplay }
关于swift - 如何将日期 "MM-dd-yyyy hh:mm:ss a"转换成文本格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46750930/