简体   繁体   中英

Swift: How to check the date is after today?

I want to limit if the date() is after today two days then allow to change.

Eg Today is 12 May 2020, the last_date is 15 May 2020, the limit is 2 days before.

So the user can change the last_date on 13 May 2020 or before.

If today is 14 May 2020, so not allow the user to change the last_date .

Sorry for the bad English grammar.

The func maybe like this:

func checkDate(_ last_date: Date) -> Bool {
    if //last_date() after today At least two days// {
        return true
    } else {
        return false
    }
}

A good way to do that is like this:

func checkDate(_ lastDate: Date) -> Bool {
    let calendar = Calendar.current

    // Replace the hour (time) of both dates with 00:00
    let startOfLastDate =  calendar.startOfDay(for: lastDate)
    let startOfToday = calendar.startOfDay(for: Date(timeIntervalSinceNow: 0))

    if let numberOfDays = calendar.dateComponents([.day], from: startOfToday, to: startOfLastDate).day {
        return numberOfDays >= 2
    } else {
        return false
    }
}

Note: The number of days return by the calendar is an optional. I choose to return false when nil is returned but you may prefer to handle it by throwing an error. Then you will be able to handle that error in your view controller to notice the user about it. To do so you can use the following:

enum dateError: Error {
    case numberOfDays
}

func checkDate(_ lastDate: Date) throws -> Bool {
    let calendar = Calendar.current

    // Replace the hour (time) of both dates with 00:00
    let startOfLastDate =  calendar.startOfDay(for: lastDate)
    let startOfToday = calendar.startOfDay(for: Date(timeIntervalSinceNow: 0))

    if let numberOfDays = calendar.dateComponents([.day], from: startOfToday, to: startOfLastDate).day {
        return numberOfDays >= 2
    } else {
        throw dateError.numberOfDays
    }
}

But in the end what I would prefer in this case would be to throw a fatalError. Since we are explicitly asking the dateComponents to extract the days, it should return it. So what I would do is this:

func checkDate(_ lastDate: Date) -> Bool {
    let calendar = Calendar.current

    // Replace the hour (time) of both dates with 00:00
    let startOfLastDate =  calendar.startOfDay(for: lastDate)
    let startOfToday = calendar.startOfDay(for: Date())

    if let numberOfDays = calendar.dateComponents([.day], from: startOfToday, to: startOfLastDate).day {
        return numberOfDays >= 2
    } else {
        fatalError("The number of days should not be nil.")
    }
}

If you want to know if a date is two days after another date you can define a function like this:

func isDate(_ date: Date, atleastTwoDaysAfter otherDate: Date) -> Bool {
    let cal = Calendar.current
    guard let result = cal.date(byAdding: .day, value: -2, to: date) else { return false }
    return result >= otherDate
}

To find out if the date is 2 days later than today just do this:

isDate(someOtherDate, atleastTwoDaysAfter: Date())

Calculate the limit by taking the start of last date (00:00) and subtracting two days. Then compare it to current date

func checkDate(_ lastDate: Date) -> Bool {
    let calendar = Calendar.current
    if let limit = calendar.date(byAdding: .day, value: -2, to: calendar.startOfDay(for: lastDate)) {
        return Date() < limit
    }

    return false
}

There is no need to calculate the start of the day.

compare(_:to:toGranularity:) of Calendar can do the comparison pretty smoothly.

func checkDate(_ lastDate: Date) -> Bool {
    guard let threshold = Calendar.current.date(byAdding: .day, value: -2, to: lastDate) else { return false }
    return Calendar.current.compare(threshold, to: Date(), toGranularity: .day) != .orderedAscending
}

The toGranularity parameter compares the specified component (and larger components) in both operands

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM