ios 比较没有时间分量的 NSDates

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24577087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:13:54  来源:igfitidea点击:

Comparing NSDates without time component

iostimeswiftnsdatefoundation

提问by agf119105

In a swift playground, I have been using

在一个快速的操场上,我一直在使用

NSDate.date() 

But, this always appears with the time element appended. For my app I need to ignore the time element. Is this possible in Swift? How can it be done? Even if I could set the time element to be the same time on every date that would work too.

但是,这总是与附加的时间元素一起出现。对于我的应用程序,我需要忽略时间元素。这在 Swift 中可行吗?怎么做到呢?即使我可以将时间元素设置为每个日期的相同时间也可以。

Also, I am trying to compare two dates and at the moment I am using the following code:

另外,我正在尝试比较两个日期,目前我正在使用以下代码:

var earlierDate:NSDate = firstDate.earlierDate(secondDate)

Is this the only way or can I do this in a way that ignores the time element? For instance I don't want a result if they are the same day, but different times.

这是唯一的方法还是我可以忽略时间元素的方式来做到这一点?例如,如果它们是同一天但不同的时间,我不想要结果。

回答by Ashley Mills

Use this Calendarfunction to compare dates in iOS 8.0+

使用此Calendar函数比较 iOS 8.0+ 中的日期

func compare(_ date1: Date, to date2: Date, toGranularity component: Calendar.Component) -> ComparisonResult


passing .dayas the unit


传递.day为单位

Use this function as follows:

使用此功能如下:

let now = Date()
// "Sep 23, 2015, 10:26 AM"
let olderDate = Date(timeIntervalSinceNow: -10000)
// "Sep 23, 2015, 7:40 AM"

var order = Calendar.current.compare(now, to: olderDate, toGranularity: .hour)

switch order {
case .orderedDescending:
    print("DESCENDING")
case .orderedAscending:
    print("ASCENDING")
case .orderedSame:
    print("SAME")
}

// Compare to hour: DESCENDING

var order = Calendar.current.compare(now, to: olderDate, toGranularity: .day)


switch order {
case .orderedDescending:
    print("DESCENDING")
case .orderedAscending:
    print("ASCENDING")
case .orderedSame:
    print("SAME")
}

// Compare to day: SAME

回答by slamor

There are several useful methods in NSCalendar in iOS 8.0+:

iOS 8.0+ 中的 NSCalendar 有几个有用的方法:

startOfDayForDate, isDateInToday, isDateInYesterday, isDateInTomorrow

And even to compare days:

甚至比较天数:

func isDate(date1: NSDate!, inSameDayAsDate date2: NSDate!) -> Bool

To ignore the time element you can use this:

要忽略时间元素,您可以使用:

var toDay = Calendar.current.startOfDay(for: Date())

But, if you have to support also iOS 7, you can always write an extension

但是,如果您还必须支持 iOS 7,您可以随时编写扩展程序

extension NSCalendar {
    func myStartOfDayForDate(date: NSDate!) -> NSDate!
    {
        let systemVersion:NSString = UIDevice.currentDevice().systemVersion
        if systemVersion.floatValue >= 8.0 {
            return self.startOfDayForDate(date)
        } else {
            return self.dateFromComponents(self.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: date))
        }
    }
}

回答by Emmett Corman

I wrote the following method to compare two dates by borrowing from Ashley Mills solution. It compares two dates and returns true if the two dates are the same (stripped of time).

我编写了以下方法,通过借鉴 Ashley Mills 的解决方案来比较两个日期。它比较两个日期,如果两个日期相同(去掉时间),则返回 true。

func compareDate(date1:NSDate, date2:NSDate) -> Bool {
    let order = NSCalendar.currentCalendar().compareDate(date1, toDate: date2,
        toUnitGranularity: .Day)
    switch order {
    case .OrderedSame:
        return true
    default:
        return false
    }
}

And it is called like this:

它是这样调用的:

if compareDate(today, date2: anotherDate) {
    // The two dates are on the same day.
}

回答by zs2020

In Swift 4:

在 Swift 4 中:

func compareDate(date1:Date, date2:Date) -> Bool {
    let order = NSCalendar.current.compare(date1, to: date2, toGranularity: .day)
    switch order {
    case .orderedSame:
        return true
    default:
        return false
    }
}

回答by abhi

Two Dates comparisions in swift.

快速比较两个日期。

    // Date comparision to compare current date and end date.
    var dateComparisionResult:NSComparisonResult = currentDate.compare(endDate)

    if dateComparisionResult == NSComparisonResult.OrderedAscending
    {
        // Current date is smaller than end date.
    }
    else if dateComparisionResult == NSComparisonResult.OrderedDescending
    {
        // Current date is greater than end date.
    }
    else if dateComparisionResult == NSComparisonResult.OrderedSame
    {
        // Current date and end date are same.
    }

回答by Loganathan

For iOS7 support

对于 iOS7 支持

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date1String = dateFormatter.stringFromDate(date1)
let date2String = dateFormatter.stringFromDate(date2)
if date1String == date2String {
    println("Equal date")
}

回答by Leo Dabus

You can compare two dates using it's description.

您可以使用它的描述来比较两个日期。

let date1 = NSDate()
let date2 = NSDate(timeIntervalSinceNow: 120)
if date1.description == date2.description {
    print(true)
} else {
    print(false)   // false (I have added 2 seconds between them)
}

If you want set the time element of your dates to a different time you can do as follow:

如果要将日期的时间元素设置为不同的时间,可以执行以下操作:

extension NSDate {
    struct Calendar {
        static let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    }
    var day:    Int { return Calendar.gregorian.component(.Day,    fromDate: self)   }
    var month:  Int { return Calendar.gregorian.component(.Month,  fromDate: self)  }
    var year:   Int { return Calendar.gregorian.component(.Year,   fromDate: self)  }

    var noon: NSDate {
        return Calendar.gregorian.dateWithEra(1, year: year, month: month, day: day, hour: 12, minute: 0, second: 0, nanosecond: 0)!
    }
}

let date1 = NSDate()
let date2 = NSDate(timeIntervalSinceNow: 120)
print(date1.noon == date2.noon)   // true

or you can also do it using NSDateFormatter:

或者你也可以使用 NSDateFormatter 来做到这一点:

extension NSDate {
    struct Date {
        static let formatterYYYYMMDD: NSDateFormatter = {
            let formatter = NSDateFormatter()
            formatter.dateFormat = "yyyyMMdd"
            return formatter
        }()
    }
    var yearMonthDay: String {
        return Date.formatterYYYYMMDD.stringFromDate(self)
    }
    func isSameDayAs(date:NSDate) -> Bool {
        return yearMonthDay == date.yearMonthDay
    }
}

let date1 = NSDate()
let date2 = NSDate(timeIntervalSinceNow: 120)
print(date1.yearMonthDay == date2.yearMonthDay)   // true

print(date1.isSameDayAs(date2))    // true

Another option (iOS8+) is to use calendar method isDate(inSameDayAsDate:):

另一种选择(iOS8+)是使用日历方法 isDate(inSameDayAsDate:):

extension NSDate {
    struct Calendar {
        static let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    }
    func isInSameDayAs(date date: NSDate) -> Bool {
        return Calendar.gregorian.isDate(self, inSameDayAsDate: date)
    }
}
let date1 = NSDate()
let date2 = NSDate(timeIntervalSinceNow: 120)
if date1.isInSameDayAs(date: date2 ){
    print(true)   // true
} else {
    print(false)
}

回答by Adrian

I wrote a Swift 4 extension for comparing two dates:

我写了一个 Swift 4 扩展来比较两个日期:

import Foundation

extension Date {      
  func isSameDate(_ comparisonDate: Date) -> Bool {
    let order = Calendar.current.compare(self, to: comparisonDate, toGranularity: .day)
    return order == .orderedSame
  }

  func isBeforeDate(_ comparisonDate: Date) -> Bool {
    let order = Calendar.current.compare(self, to: comparisonDate, toGranularity: .day)
    return order == .orderedAscending
  }

  func isAfterDate(_ comparisonDate: Date) -> Bool {
    let order = Calendar.current.compare(self, to: comparisonDate, toGranularity: .day)
    return order == .orderedDescending
  }
}

Usage:

用法:

startDate.isSameDateAs(endDate) // returns a true or false

startDate.isSameDateAs(endDate) // returns a true or false

回答by Uzma

For Swift3

对于 Swift3

var order = NSCalendar.current.compare(firstDate, to: secondDate, toGranularity: .hour)

if order == .orderedSame {
    //Both the dates are same. 
    //Your Logic.
}

回答by Maciej

Swift 3

斯威夫特 3

        let order = NSCalendar.current.compare(date1, to: date2, toGranularity: .day)

        if order == .orderedAscending { 
          // date 1 is older
        }
        else if order == .orderedDescending { 
          // date 1 is newer
        }
        else if order == .orderedSame { 
          // same day/hour depending on granularity parameter
        }