swift 工具类(一)时间格式化,昨天,今天和明天

func timeintervalToDate(interval:String) -> String {
        let timeString = NSString(string: interval)
        let range = _NSRange(location: 0, length: 10)
        let suString = timeString.substringWithRange(range)
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:MM:ss"
        let date = NSDate(timeIntervalSince1970: Double(suString)!)
        return self.compareDate(date)
    }
    func compareDate(oldDate:NSDate) -> String{
//8小时时差
        let now = NSDate()
        let zone = NSTimeZone.systemTimeZone()
        let interval = zone.secondsFromGMTForDate(now)
        let localeDate = now.dateByAddingTimeInterval(Double(interval))
        let today = localeDate
        
        let newDate = oldDate.dateByAddingTimeInterval(Double(interval))
        
        let secondsPerDay:NSTimeInterval = 24 * 60 * 60
        let yesterday = today.dateByAddingTimeInterval(-secondsPerDay)
        let beforeOfYesterday = yesterday.dateByAddingTimeInterval(-secondsPerDay)
        let dateString = NSString(string: newDate.description).substringToIndex(10)
        let todayString = NSString(string: today.description).substringToIndex(10)
        let yesterdayString = NSString(string: yesterday.description).substringToIndex(10)
        let beforeOfYesterdayString = NSString(string: beforeOfYesterday.description).substringToIndex(10);
        let toYears = NSString(string: today.description).substringToIndex(4)
        let dateYears = NSString(string: newDate.description).substringToIndex(4)
        let timeH = NSString(string: newDate.description).substringWithRange(_NSRange(location: 11, length: 5))
        let timeG = NSString(string: newDate.description).substringWithRange(_NSRange(location: 5, length: 11))
        if toYears == dateYears {
            if dateString == todayString {
                return "今天 \(timeH)"
            } else if dateString == yesterdayString {
                return "昨天 \(timeH)"
            } else if dateString == beforeOfYesterdayString {
                return "前天 \(timeH)"
            } else {
                return timeG
            }
        } else {
            return dateString
        }
    }


你可能感兴趣的:(swift 工具类(一)时间格式化,昨天,今天和明天)