Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two NSDates day, month and year integers

Tags:

ios

swift

I am trying to compare two NSDates to understand if they are in the same day or not. These are the two dates (the second one is always the current date, NSDate()):

2015-08-23 22:00:00 +0000 2015-08-23 19:13:45 +0000

It seems obvious that the dates are in the same day, as 23 = 23. However I can't seem to be able to establish this in the code. I tried:

1)

let date = tripObject["tripDate"] as! NSDate
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let str = dateFormatter.stringFromDate(date)

let date2 = NSDate()
let dateFormatter2 = NSDateFormatter()
dateFormatter2.dateFormat = "yyyy-MM-dd"
let str2 = dateFormatter2.stringFromDate(date2)

println(". \(str) and \(str2) .")

This gives 2015-08-24 and 2015-08-23

2)

let dateComponents = NSCalendar.currentCalendar().components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: tripObject["tripDate"] as! NSDate)
let dateComponents2 = NSCalendar.currentCalendar().components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: NSDate())

This gives different day components.

3)

if NSCalendar.currentCalendar().isDate(firstDate!, inSameDayAsDate: secondDate!){ 

4)

if NSCalendar.currentCalendar().isDateInToday(the NSDate) {

Both 3 and 4 fail.

I am totally lost, any ideas?

like image 737
Alessandro Avatar asked Dec 06 '22 20:12

Alessandro


1 Answers

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)
like image 92
vadian Avatar answered Dec 24 '22 15:12

vadian