计算NSDate swift 2之间的持续时间

时间:2015-10-26 15:26:20

标签: ios nsdate swift2.1

在通知中,您会看到显示“5分钟前发布”的活动, 这就是我想在这里实现的目标。以下功能正常运作。

func daysBetweenDate(startDate: NSDate, endDate: NSDate) -> Int
{
    let calendar = NSCalendar.currentCalendar()

    let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])
//    print(components.second)
    return components.day
}

daysBetweenDate(postedDate, endDate: NSDate())

func hoursBetweenDate(startDate: NSDate, endDate: NSDate) -> Int
{
    let calendar = NSCalendar.currentCalendar()

    let components = calendar.components([.Hour], fromDate: startDate, toDate: endDate, options: [])
    //    print(components.second)
    return components.hour
}

hoursBetweenDate(postedDate, endDate: NSDate())

如何识别postedDate是否已经是秒,分钟,小时或日期。并返回任何必要的?

如果两个NSDates之间的持续时间超过一分钟,我想输出“34分钟前”,当它超过一小时,“2小时前”,依此类推。我怎么能有条件地做到这一点。

1 个答案:

答案 0 :(得分:2)

给出两个日期,你可以用NSDateComponentsFormatter非常好地完成这个:

let form = NSDateComponentsFormatter()
form.maximumUnitCount = 1
form.unitsStyle = .SpellOut // or .Full, whatever you prefer
let s = form.stringFromTimeInterval(
    d1.timeIntervalSinceReferenceDate - d2.timeIntervalSinceReferenceDate)