【问题标题】:How to check if two NSDates are from the same day [duplicate]如何检查两个NSDate是否来自同一天[重复]
【发布时间】:2016-05-25 02:03:49
【问题描述】:

我正在开发 ios,我发现很难检查两个 NSDate 是否来自同一天。我试过用这个

   fetchDateList()
    // Check date
    let date = NSDate()
    // setup date formatter
    let dateFormatter = NSDateFormatter()
    // set current time zone
    dateFormatter.locale = NSLocale.currentLocale()

    let latestDate = dataList[dataList.count-1].valueForKey("representDate") as! NSDate
    //let newDate = dateFormatter.stringFromDate(date)
    let diffDateComponent = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: latestDate, toDate: date, options: NSCalendarOptions.init(rawValue: 0))
    print(diffDateComponent.day)

但它只是检查两个 NSDate 是否相差 24 小时。我认为有一种方法可以让它工作,但我仍然希望在凌晨 2 点之前将 NSDate 值算作前一天,所以我在这里肯定需要一些帮助。谢谢!

【问题讨论】:

    标签: ios swift nsdate


    【解决方案1】:

    NSCalendar 有一个方法可以完全按照您的实际需要进行操作!

    /*
        This API compares the Days of the given dates, reporting them equal if they are in the same Day.
    */
    - (BOOL)isDate:(NSDate *)date1 inSameDayAsDate:(NSDate *)date2 NS_AVAILABLE(10_9, 8_0);
    

    所以你会这样使用它:

    [[NSCalendar currentCalendar] isDate:date1 inSameDayAsDate:date2];
    

    或者在 Swift 中

    Calendar.current.isDate(date1, inSameDayAs:date2)
    

    【讨论】:

    • 小更新:在 Swift 3.0 Xcode 8.2 中语法:if NSCalendar.current.isDate(date1, inSameDayAs:date2) == true) { // do your stuff}
    • 它似乎不适用于 2017-06-12T00:00:00.000Z2017-06-12T23:59:59.999Z 这样的特定日期 --> "23:59:59" 由于某种原因进入第二天(我的时区是 +2,并且21:59:59 工作正常)。似乎对时区做了一些事情,但我还没有想出如何让它发挥作用。
    • 这是夏令时过渡吗?如果是这样,那一天可能只有 23 小时。
    • 有什么可以解决的吗?我描述的是正确的行为;这一天确实每年提前一个小时结束。
    • 除了不必编写自己的代码的明显便利性之外,内置方法的速度令人愉悦,几乎是比较日期组件的两倍。
    【解决方案2】:

    您应该比较日期组件:

    let date1 = NSDate(timeIntervalSinceNow: 0)
    let date2 = NSDate(timeIntervalSinceNow: 3600)
    
    let components1 = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: date1)
    let components2 = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: date2)
    
    if components1.year == components2.year && components1.month == components2.month && components1.day == components2.day {
        print("same date")
    } else {
        print("different date")
    }
    

    或更短:

    let diff = Calendar.current.dateComponents([.day], from: self, to: date)
    if diff.day == 0 {
        print("same day")
    } else {
        print("different day")
    }
    

    【讨论】:

    • 这适用于不同的时区吗?
    • 如果时区不同,请将components替换为componentsInTimeZone(_, fromDate: _)
    • 你可以比较if components1 == components2 {
    猜你喜欢
    • 2010-12-06
    • 1970-01-01
    • 2016-01-24
    • 2013-07-29
    • 1970-01-01
    • 2015-06-12
    • 2016-04-11
    • 2010-11-07
    相关资源
    最近更新 更多