码迷,mamicode.com
首页 > 编程语言 > 详细

swift 显示友好时间

时间:2014-12-25 23:40:49      阅读:217      评论:0      收藏:0      [点我收藏+]

标签: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 显示友好时间

标签:swift   友好时间   时间转换   

原文地址:http://blog.csdn.net/zhyl8157121/article/details/42155921

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!