Nice programing

Swift 3-날짜 객체 비교

nicepro 2020. 9. 25. 23:37
반응형

Swift 3-날짜 객체 비교


내 앱을 Swift 3.0 구문으로 업데이트하고 있습니다 (아직 베타 버전이지만 출시 되 자마자 준비하고 싶습니다).

엑스 코드 (베타 5)의 이전 베타 때까지 나는이 비교할 수 있었다 Date피연산자를 사용하여 객체를 <, >하고 ==. 그러나 최신 베타 (베타 6)에서는 더 이상 작동하지 않습니다. 다음은 몇 가지 스크린 샷입니다.

여기에 이미지 설명 입력 여기에 이미지 설명 입력

두 스크린 샷에서 볼 수 있듯이 두 Date개체가 있습니다. 하지만 다음과 같은 오류가 발생합니다.여기에 이미지 설명 입력

내가 뭘 잘못하고 있죠? 함수는 여전히 Date클래스 에서 선언됩니다 .

static func >(Date, Date)

왼쪽 Date가 오른쪽 Date보다 늦은 경우 true를 반환합니다.

이것은 베타 버그입니까, 아니면 내가 뭘 잘못하고 있습니까?


이 스 니펫 (XCode 8 Beta 6에서)을 시도했으며 정상적으로 작동합니다.

let date1 = Date()
let date2 = Date().addingTimeInterval(100)

if date1 == date2 { ... }
else if date1 > date2 { ... }
else if date1 < date2 { ... }

Dateis Comparable& Equatable(Swift 3 기준)

이 답변은 @Ankit Thakur의 답변을 보완합니다.

Swift 3 이후 Date구조체 (기본 NSDate클래스 기반 )는 ComparableEquatable프로토콜을 채택합니다 .

  • Comparable즉 필요 Date연산자를 구현 : <, <=, >, >=.
  • Equatable운영자 Date구현 해야합니다 ==.
  • Equatable연산자 Date의 기본 구현을 사용할 수 있습니다 !=( Equatable ==연산자 구현의 역임).

다음 샘플 코드는 이러한 비교 연산자를 실행하고 print문과 어떤 비교가 참인지 확인 합니다.

비교 기능

import Foundation

func describeComparison(date1: Date, date2: Date) -> String {

    var descriptionArray: [String] = []

    if date1 < date2 {
        descriptionArray.append("date1 < date2")
    }

    if date1 <= date2 {
        descriptionArray.append("date1 <= date2")
    }

    if date1 > date2 {
        descriptionArray.append("date1 > date2")
    }

    if date1 >= date2 {
        descriptionArray.append("date1 >= date2")
    }

    if date1 == date2 {
        descriptionArray.append("date1 == date2")
    }

    if date1 != date2 {
        descriptionArray.append("date1 != date2")
    }

    return descriptionArray.joined(separator: ",  ")
}

샘플 사용

let now = Date()

describeComparison(date1: now, date2: now.addingTimeInterval(1))
// date1 < date2,  date1 <= date2,  date1 != date2

describeComparison(date1: now, date2: now.addingTimeInterval(-1))
// date1 > date2,  date1 >= date2,  date1 != date2

describeComparison(date1: now, date2: now)
// date1 <= date2,  date1 >= date2,  date1 == date2

from Swift 3 and above, Date is Comparable so we can directly compare dates like

let date1 = Date()
let date2 = Date()

let isGreater = date1 > date2
print(isGreater)

let isSmaller = date1 < date2
print(isSmaller)

let isEqual = date1 == date2
print(isEqual)

Alternatively We can create extension on Date

extension Date {

  func isEqualTo(_ date: Date) -> Bool {
    return self == date
  }

  func isGreaterThan(_ date: Date) -> Bool {
     return self > date
  }

  func isSmallerThan(_ date: Date) -> Bool {
     return self < date
  }
}

Use: let isEqual = date1.isEqualTo(date2)


Look this http://iswift.org/cookbook/compare-2-dates

Get Dates:

// Get current date
let dateA = NSDate()

// Get a later date (after a couple of milliseconds)
let dateB = NSDate()

Using SWITCH Statement

// Compare them
switch dateA.compare(dateB) {
    case .OrderedAscending     :   print("Date A is earlier than date B")
    case .OrderedDescending    :   print("Date A is later than date B")
    case .OrderedSame          :   print("The two dates are the same")
}

using IF Statement

 if dateA.compare(dateB) == .orderedAscending {
     datePickerTo.date = datePicker.date
 }

 //OR

 if case .orderedAcending = dateA.compare(dateB) {

 }

For me the problem was that I had my own extension to Date class that was defining all the compare operators. Now (since swift 3) that Date is comparable, these extensions are not needed. So I commented them out and it worked.


SWIFT 3: Don't know if this is what you're looking for. But I compare a string to a current timestamp to see if my string is older that now.

func checkTimeStamp(date: String!) -> Bool {
        let dateFormatter: DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.locale = Locale(identifier:"en_US_POSIX")
        let datecomponents = dateFormatter.date(from: date)

        let now = Date()

        if (datecomponents! >= now) {
            return true
        } else {
            return false
        }
    }

To use it:

if (checkTimeStamp(date:"2016-11-21 12:00:00") == false) {
    // Do something
}

To compare date only with year - month - day and without time for me worked like this:

     let order = Calendar.current.compare(self.startDate, to: compareDate!, toGranularity: .day)  

                      switch order {
                        case .orderedAscending:
                            print("\(gpsDate) is after \(self.startDate)")
                        case .orderedDescending:
                            print("\(gpsDate) is before \(self.startDate)")
                        default:
                            print("\(gpsDate) is the same as \(self.startDate)")
                        }

As of the time of this writing, Swift natively supports comparing Dates with all comparison operators (i.e. <, <=, ==, >=, and >). You can also compare optional Dates but are limited to <, ==, and >. If you need to compare two optional dates using <= or >=, i.e.

let date1: Date? = ...
let date2: Date? = ...
if date1 >= date2 { ... }

You can overload the <= and >=operators to support optionals:

func <= <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
    return lhs == rhs || lhs < rhs
}

func >= <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
    return lhs == rhs || lhs > rhs
}

extension Date {
 func isBetween(_ date1: Date, and date2: Date) -> Bool {
    return (min(date1, date2) ... max(date1, date2)).contains(self)
  }
}

let resultArray = dateArray.filter { $0.dateObj!.isBetween(startDate, and: endDate) }

Another way to do it:

    switch date1.compare(date2) {
        case .orderedAscending:
            break

        case .orderedDescending:
            break;

        case .orderedSame:
            break
    }

   var strDateValidate = ""
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"

            let firstDate = dateFormatter.date(from:lblStartTime.text!)
            let secondDate = dateFormatter.date(from:lblEndTime.text!)

            if firstDate?.compare(secondDate!) == .orderedSame || firstDate?.compare(secondDate!) == .orderedAscending {
                print("Both dates are same or first is less than scecond")
                strDateValidate = "yes"
            }
            else
            {
                //second date is bigger than first
                strDateValidate = "no"
            }

            if strDateValidate == "no"
            {
                alertView(message: "Start date and end date for a booking must be equal or Start date must be smaller than the end date", controller: self)
            }

Swift 5:

1) If you use Date type:

let firstDate  = Date()
let secondDate = Date()

print(firstDate > secondDate)  
print(firstDate < secondDate)
print(firstDate == secondDate)

2) If you use String type:

let firstStringDate  = "2019-05-22T09:56:00.1111111"
let secondStringDate = "2019-05-22T09:56:00.2222222"

print(firstStringDate > secondStringDate)  // false
print(firstStringDate < secondStringDate)  // true
print(firstStringDate == secondStringDate) // false 

I'm not sure or the second option works at 100%. But how much would I not change the values of firstStringDate and secondStringDate the result was correct.

참고URL : https://stackoverflow.com/questions/39018335/swift-3-comparing-date-objects

반응형