Nsdate Comparison Using Swift

NSDate Comparison using Swift

I like using extensions to make code more readable. Here are a few NSDate extensions that can help clean your code up and make it easy to understand. I put this in a sharedCode.swift file:

extension NSDate {

func isGreaterThanDate(dateToCompare: NSDate) -> Bool {
//Declare Variables
var isGreater = false

//Compare Values
if self.compare(dateToCompare as Date) == ComparisonResult.orderedDescending {
isGreater = true
}

//Return Result
return isGreater
}

func isLessThanDate(dateToCompare: NSDate) -> Bool {
//Declare Variables
var isLess = false

//Compare Values
if self.compare(dateToCompare as Date) == ComparisonResult.orderedAscending {
isLess = true
}

//Return Result
return isLess
}

func equalToDate(dateToCompare: NSDate) -> Bool {
//Declare Variables
var isEqualTo = false

//Compare Values
if self.compare(dateToCompare as Date) == ComparisonResult.orderedSame {
isEqualTo = true
}

//Return Result
return isEqualTo
}

func addDays(daysToAdd: Int) -> NSDate {
let secondsInDays: TimeInterval = Double(daysToAdd) * 60 * 60 * 24
let dateWithDaysAdded: NSDate = self.addingTimeInterval(secondsInDays)

//Return Result
return dateWithDaysAdded
}

func addHours(hoursToAdd: Int) -> NSDate {
let secondsInHours: TimeInterval = Double(hoursToAdd) * 60 * 60
let dateWithHoursAdded: NSDate = self.addingTimeInterval(secondsInHours)

//Return Result
return dateWithHoursAdded
}
}

Now if you can do something like this:

//Get Current Date/Time
var currentDateTime = NSDate()

//Get Reminder Date (which is Due date minus 7 days lets say)
var reminderDate = dueDate.addDays(-7)

//Check if reminderDate is Greater than Right now
if(reminderDate.isGreaterThanDate(currentDateTime)) {
//Do Something...
}

Swift 3 - Comparing Date objects

I have tried this snippet (in Xcode 8 Beta 6), and it is working fine.

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

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

How can i compare two dates (NSDate) in Swift 3 and get the days between them?

Simply make extension of Date like this and get difference in days.

extension Date {
func daysBetweenDate(toDate: Date) -> Int {
let components = Calendar.current.dateComponents([.day], from: self, to: toDate)
return components.day ?? 0
}
}

Now use this extension like this

let numOfDays = fromDate.daysBetweenDate(toDate: toDate)

You can use DateFormatter to convert String to Date like this.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
let date = dateFormatter.date(from: "18-11-2016")

Compare two NSDate by .Day in swift is giving wrong results

Those two logged dates are being logged in the UTC timezone. But if your current timezone is west of that, then both dates are on March 8, 2016 in your timezone and the comparison is done in your timezone. Or, if you live east of that by at least 2.5 hours, then both dates are March 9, 2016.

Example. If you live in the eastern USA (GMT-4 currently but GMT-5 on March 8), then those two dates are actually 2016-03-08 16:43:53 -0500 and 2016-03-08 19:00:00 -0500.

Example. If you live in eastern Europe or Asia (say GMT+5), then those two dates would be 2016-03-09 02:43:53 +0500 and 2016-03-09 05:00:00 +0500.

As you can see, those are on the same day so the comparison is correct.

Comparing two NSDates day, month and year integers

NSCalendar has a method isDate:equalToDate:toUnitGranularity: which does exactly what you need

date1 and date2 are the NSDate instances to be compared, the result is Bool

let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let datesAreInTheSameDay = calendar.isDate(date1, equalToDate: date2, toUnitGranularity: .CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear)

Swift 2:

let datesAreInTheSameDay = calendar.isDate(date1, equalToDate: date2, toUnitGranularity: [.Day, .Month, .Year])

Swift 3:

var calendar = Calendar.current
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
let datesAreInTheSameDay = calendar.isDate(date1, equalTo: date2, toGranularity:.day)

Compare Date to String Date Value Swift

There is a better way to check if two dates are in the same day

let currentDate = Date()
let selectedDate = Date()
if Calendar.current.isDate(currentDate, inSameDayAs: selectedDate) {
print("yes")
} else {
print("no")
}


Related Topics



Leave a reply



Submit