Swift 3 好友消息时间处理

Swift 3 好友消息时间处理_第1张图片
demo.png

如图,类似qq微信好友消息时间展示,方法封装在'String'分类,使用起来比较简单

import UIKit
extension String {

public func friendlyTime(dateTime: String) -> String {
        
        let dateFormatter = DateFormatter()
        dateFormatter.locale = NSLocale(localeIdentifier: "zh_CN") as Locale!
        dateFormatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd HH:mm:ss")
        if let date = dateFormatter.date(from: dateTime) {
            let delta = NSDate().timeIntervalSince(date)
            
            if (delta <= 0) {
                return "刚刚"
            }
            else if (delta < 60) {
                return "\(Int(delta))秒前"
            }
            else if (delta < 3600) {
                return "\(Int(delta / 60))分钟前"
            }
            else {
                let calendar = NSCalendar.current
                let unitFlags = Set([.year,.month,.day,.hour,.minute])
                let comp = calendar.dateComponents(unitFlags, from: Date())
                
                let currentYear = String(comp.year!)
                let currentDay = String(comp.day!)
                
                let comp2 = calendar.dateComponents(unitFlags, from: 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 timeInterval : Int64 = message1!.timestamp
if timeInterval > 140000000000 {
    timeInterval = timeInterval / 1000
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    latestMessageTime = formatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(timeInterval)))
    cell.timeLabel.text = latestMessageTime.friendlyTime(dateTime: latestMessageTime)
}

原文地址

你可能感兴趣的:(Swift 3 好友消息时间处理)