首页 > 代码库 > swift 显示友好时间
swift 显示友好时间
需求:
swift开发,想显示如「24秒前」、「15分钟前」、「今天 14:15」这样的时间称呼。
直接上代码
func friendlyTime(dateTime: String) -> String { let dateFormatter = NSDateFormatter() dateFormatter.locale = NSLocale(localeIdentifier: "zh_CN") dateFormatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd HH:mm:ss") if let date = dateFormatter.dateFromString(dateTime) { let delta = NSDate().timeIntervalSinceDate(date) if (delta <= 0) { return "刚刚" } else if (delta < 60) { return "\(Int(delta))秒前" } else if (delta < 3600) { return "\(Int(delta / 60))分钟前" } else { let calendar = NSCalendar.currentCalendar() let unitFlags = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute let comp = calendar.components(unitFlags, fromDate: NSDate()) let currentYear = String(comp.year) let currentDay = String(comp.day) let comp2 = calendar.components(unitFlags, fromDate: date) let year = String(comp2.year) let month = String(comp2.month) let day = String(comp2.day) var hour = String(comp2.hour) var minute = String(comp2.minute) if comp2.hour < 10 { hour = "0" + hour } if comp2.minute < 10 { minute = "0" + minute } if currentYear == year { if currentDay == day { return "今天 \(hour):\(minute)" } else { return "\(month)月\(day)日 \(hour):\(minute)" } } else { return "\(year)年\(month)月\(day)日 \(hour):\(minute)" } } } return "" }
调用
var dateTime = "2014-12-25 23:07:12" friendlyTime(dateTime)
swift 显示友好时间
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。