static func dateFormatter() -> NSDateFormatter {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "zh_CN")
dateFormatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd HH:mm:ss")
return dateFormatter
}
static func timestampByString(createdTime: String) -> String {
let date = dateFormatter().dateFromString(createdTime)
return timestampByDate(date)
}
static func timestampByDate(createdTime: NSDate?) -> String {
var timestamp = String()
if let date = createdTime {
var distance = NSDate().timeIntervalSinceDate(date)
if distance < 60 * 5 {
timestamp = "刚刚"
}
else if distance < 60 * 60 {
distance = distance / 60
timestamp = "\(Int(distance)) 分钟前"
} else {
let calendar = NSCalendar.currentCalendar()
let unitFlags: NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute]
let nowComp = calendar.components(unitFlags, fromDate: NSDate())
let currentYear = String(nowComp.year)
let currentDay = String(nowComp.day)
let timeComp = calendar.components(unitFlags, fromDate: date)
let year = String(timeComp.year)
var month = String(timeComp.month)
var day = String(timeComp.day)
var hour = String(timeComp.hour)
var minute = String(timeComp.minute)
if timeComp.month < 10 {
month = "0" + month
}
if timeComp.day < 10 {
day = "0" + day
}
if timeComp.hour < 10 {
hour = "0" + hour
}
if timeComp.minute < 10 {
minute = "0" + minute
}
if currentYear == year {
if currentDay == day {
timestamp = "\(hour):\(minute)"
} else {
timestamp = "\(year)-\(month)-\(day) \(hour):\(minute)"
}
} else {
timestamp = "\(year)-\(month)-\(day) \(hour):\(minute)"
}
}
}
return timestamp
}