0

在通知中,您会看到显示“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 是否已经是秒、分钟、小时或天。并返回任何必要的?

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

4

1 回答 1

2

给两个日期,你可以用 NSDateComponentsFormatter 很好地做到这一点:

let form = NSDateComponentsFormatter()
form.maximumUnitCount = 1
form.unitsStyle = .SpellOut // or .Full, whatever you prefer
let s = form.stringFromTimeInterval(
    d1.timeIntervalSinceReferenceDate - d2.timeIntervalSinceReferenceDate)
于 2015-10-26T15:53:57.880 回答