Swift - 检查时间戳是昨天,今天,明天还是X天前

时间:2016-09-06 09:13:35

标签: ios swift nsdate nscalendar

我正在尝试确定如何确定今天是否发生给定时间戳,或+1 / -1天。基本上,我想做这样的事情(Pseudocode)

IF days_from_today(timestamp) == -1 RETURN 'Yesterday'
ELSE IF days_from_today(timestamp) == 0 RETURN 'Today'
ELSE IF days_from_today(timestamp) == 1 RETURN 'Tomorrow'
ELSE IF days_from_today(timestamp) < 1 RETURN days_from_today(timestamp) + ' days ago'
ELSE RETURN 'In ' + days_from_today(timestamp) + ' ago'

至关重要的是,它需要在Swift中,我正在努力使用NSDate / NSCalendar对象。我开始研究这样的时差:

let calendar = NSCalendar.currentCalendar()
let date = NSDate(timeIntervalSince1970: Double(timestamp))
let timeDifference = calendar.components([.Second,.Minute,.Day,.Hour],
    fromDate: date, toDate: NSDate(), options: NSCalendarOptions())

然而,以这种方式进行比较并不容易,因为.Day根据一天中的时间和时间戳而有所不同。在PHP中,我只是使用mktime来创建一个基于当天开始的新日期(即mktime(0,0,0)),但我不确定在Swift中最简单的方法。

有没有人对如何处理这个问题有个好主意?也许NSDate的扩展或类似的东西最好?

6 个答案:

答案 0 :(得分:79)

Calendar包含所有三种情况的方法

func isDateInYesterday(_ date: Date) -> Bool
func isDateInToday(_ date: Date) -> Bool
func isDateInTomorrow(_ date: Date) -> Bool

要计算比昨天更早的天数,请使用

func dateComponents(_ components: Set<Calendar.Component>, 
                      from start: Date, 
                          to end: Date) -> DateComponents

[.day]传递给components并从结果中获取day属性。

这是一个通过剥离时间部分(Swift 3 +)来考虑早期和晚期日期的is in的函数。

func dayDifference(from interval : TimeInterval) -> String
{
    let calendar = Calendar.current
    let date = Date(timeIntervalSince1970: interval)
    if calendar.isDateInYesterday(date) { return "Yesterday" }
    else if calendar.isDateInToday(date) { return "Today" }
    else if calendar.isDateInTomorrow(date) { return "Tomorrow" }
    else {
        let startOfNow = calendar.startOfDay(for: Date())
        let startOfTimeStamp = calendar.startOfDay(for: date)
        let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
        let day = components.day!
        if day < 1 { return "\(-day) days ago" }
        else { return "In \(day) days" }
    }
}

或者,您可以将DateFormatter用于昨天今天明天以免费获取本地化字符串

func dayDifference(from interval : TimeInterval) -> String
{
    let calendar = Calendar.current
    let date = Date(timeIntervalSince1970: interval)
    let startOfNow = calendar.startOfDay(for: Date())
    let startOfTimeStamp = calendar.startOfDay(for: date)
    let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
    let day = components.day!
    if abs(day) < 2 {
        let formatter = DateFormatter()
        formatter.dateStyle = .short
        formatter.timeStyle = .none
        formatter.doesRelativeDateFormatting = true
        return formatter.string(from: date)
    } else if day > 1 {
        return "In \(day) days"
    } else {
        return "\(-day) days ago"
    }
}

答案 1 :(得分:78)

Swift 3/4:

Calendar.current.isDateInToday(yourDate)
Calendar.current.isDateInYesterday(yourDate)
Calendar.current.isDateInTomorrow(yourDate)

此外:

Calendar.current.isDateInWeekend(yourDate)

请注意,对于某些国家/地区,周末可能与周六至周日不同,具体取决于日历。

您还可以使用autoupdatingCurrent代替current日历来跟踪用户更新。你以同样的方式使用它:

Calendar.autoupdatingCurrent.isDateInToday(yourDate)

CalendarNSCalendar的类型别名。

答案 2 :(得分:13)

Swift 4更新:

    let calendar = Calendar.current
    let date = Date()

    calendar.isDateInYesterday(date)
    calendar.isDateInToday(date)
    calendar.isDateInTomorrow(date)

答案 3 :(得分:6)

NSCalender提供了可以直接使用的新方法。

NSCalendar.currentCalendar().isDateInTomorrow(NSDate())//Replace NSDate() with your date
NSCalendar.currentCalendar().isDateInYesterday()
NSCalendar.currentCalendar().isDateInTomorrow()

希望这有帮助

答案 4 :(得分:2)

Swift 5 iOS 13 上,使用RelativeDateTimeFormatter,

let formatter = RelativeDateTimeFormatter()
formatter.dateTimeStyle = .named 

formatter.localizedString(from: DateComponents(day: -1)) // "yesterday"
formatter.localizedString(from: DateComponents(day: 1)) // "Tomorrow"
formatter.localizedString(from: DateComponents(hour: 2)) // "in 2 hours"
formatter.localizedString(from: DateComponents(minute: 45)) // "in 45 minutes"

答案 5 :(得分:0)

1)根据您的示例,您希望接收标签“ Yesterday”,“ Today”等。iOS可以默认执行以下操作:

https://developer.apple.com/documentation/foundation/nsdateformatter/1415848-doesrelativedateformatting?language=objc

2)如果要在iOS自己不添加这些标签的情况下计算自定义标签,则可以将2个DateFormatter对象与doesRelativeDateFormatting == truedoesRelativeDateFormatting == false一起使用并进行比较如果它们的结果日期字符串相同或不同