2

Comparing dates in Swift is really simple and easily understandable. It can be written in a single line, for example:

if date1 > date2

But what if I want to check if Date1 is 3 years smaller or greater than Date2?

3
  • Have a look at TimeInterval. developer.apple.com/documentation/foundation/timeinterval Commented Jun 29, 2018 at 12:45
  • let firstDateComponents = calendar.dateComponents([.day, .month, .year, .hour, .minute, .second], from: firstDate) create two date components and check the difference individually, month, day, year etc Commented Jun 29, 2018 at 12:45
  • You need to clarify your requirement here, especially since you used the word "exactly". If date1 = 2018-01-01 and date2 = 2021-12-31, should your function return true or false? The year components of the two dates differ by 3, but the actual time span between the two is almost 4 years. Similar issue if I go backward (date2 = 2015-12-31) Commented Jun 30, 2018 at 4:19

6 Answers 6

7

Try using DateComponents:

let components = Calendar.current.dateComponents([.year], from: Date(), to: secondDate)
print(components.year)
Sign up to request clarification or add additional context in comments.

Comments

5

This should do what you're asking:

func dateIsNYearsBeforeDate(date1: Date, date2: Date, nYears: Int) -> Bool {
    let calendar = Calendar.current

    // Extract the components of the dates
    let date1Components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date1)
    let date2Components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date2)

    // Check if the dates are in the same month and day
    let isSameMonth = date1Components.month == date2Components.month
    let isSameDay = date1Components.day == date2Components.day

    // Skip this if you want to check only the date and not the time
    let isSameHour = date1Components.hour == date2Components.hour
    let isSameMinute = date1Components.minute == date2Components.minute
    let isSameSecond = date1Components.second == date2Components.second

    let yearsDifference = date2Components.year! - date1Components.year!

    return isSameMonth && isSameDay && isSameHour && isSameMinute && isSameSecond && yearsDifference == nYears
}

1 Comment

you should check for typos
1

Here's the code to check if 2 dates is greater than X years. Hopefully the comments will help you understand the process. Understand the logic and modify it to suit your needs.

func isPastXYears(_ numberOfYears : Int) -> Bool{

    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy/MM/dd"

    //Determine PastDate and NowDate
    guard let pastDate = formatter.date(from: "2015/06/28") else { return false}
    let nowDate = Date()

    //Convert the dates to TimeInterval for comparing
    let pastDateTimeInterval = pastDate.timeIntervalSinceNow
    let nowDateTimeInterval = nowDate.timeIntervalSinceNow

    //Get the TimeInterval of X years
    let xYearsTimeInterval : TimeInterval = 60 * 60 * 24 * 365 * Double(numberOfYears) // seconds * minutes * hoursInADay * numberOfDaysInAYear * numberOfYears

    //Get the difference of the dates' timeinterval
    let timeIntervalDifference = nowDateTimeInterval - pastDateTimeInterval

    //Check if difference is > xYearsInterval
    return (timeIntervalDifference >= xYearsTimeInterval)
}

isPastXYears(3) //true
isPastXYears(4) //false

Comments

1

In Swift 5.0, you can compare Date structs as it conforms to Equatable and Comparable. This means you can do something like:

let now = Date()
let theFuture = Date().addingTimeInterval(100)

and check it like so:

now == theFuture
now != theFuture
now < theFuture
now > theFuture

Reference

Comments

1

Use DateComponents, like in the snippet below:

let monthsToAdd = 2
let daysToAdd = 1
let yearsToAdd = 1
let currentDate = Date()

var dateComponent = DateComponents()

dateComponent.month = monthsToAdd
dateComponent.day = daysToAdd
dateComponent.year = yearsToAdd

let futureDate = Calendar.current.date(byAdding: dateComponent, to: currentDate)

print(currentDate)
print(futureDate!)

Comments

0

I would probably do something like this:

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

let dateMinus3Years = Calendar.current.date(byAdding: .year, value: -3, to: date1)!
let datePlus3Years = Calendar.current.date(byAdding: .year, value: 3, to: date1)!
let condition = Calendar.current.isDate(date2, inSameDayAs: dateMinus3Years)
   || Calendar.current.isDate(date2, inSameDayAs: datePlus3Years)

or

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

let date1Components = Calendar.current.dateComponents([.year, .month, .day], from: date1)
let date2Components = Calendar.current.dateComponents([.year, .month, .day], from: date2)

let condition = abs(date1Components.year! - date2Components.year!) == 3
    && date1Components.month == date2Components.month
    && date1Components.day == date2Components.day

This will be safer than using time differences.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.