When trying to get the latest possible date for a day that is not the day after (i.e. 2015-03-17 23:59:59.999...), I should be able to add 1 day to the date, and then subtract a unit of least precision from the timeInterval double. This should yield the correct date, however as you can see from below, the day of that date is not consistent.
let calendar = NSCalendar.currentCalendar()
var comps = NSDateComponents()
comps.day = 17
comps.month = 3
comps.year = 2015
// Get today, tomorrow, and endOfToday
let today = calendar.dateFromComponents(comps)!
let tomorrow = calendar.dateByAddingUnit(.CalendarUnitDay, value: 1, toDate: today, options: nil)!
let intervalToday = today.timeIntervalSinceReferenceDate // 448243200
let intervalTomorrow = tomorrow.timeIntervalSinceReferenceDate // 448329600
// Get interval immediately before intervalTomorrow (subtract ULP - unit of least precision)
// nextafter intervalTomorrow in the direction of intervalToday
let endOfTodayInterval = nextafter(intervalTomorrow, intervalToday) // 448329599.9999999
let endOfToday = NSDate(timeIntervalSinceReferenceDate: endOfTodayInterval)
println(today) // 2015-03-17 00:00:00 +0000
println(tomorrow) // 2015-03-18 00:00:00 +0000
println(endOfToday) // 2015-03-18 00:00:00 +0000 !!! Hmm... should be 2015-03-17 23:59:59 +0000
// So... what day is the endOfToday!? 18th or 17th?
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "d"
dateFormatter.stringFromDate(endOfToday) // 18
calendar.component(.CalendarUnitDay, fromDate: endOfToday) // 17
// Hmm...
Does anyone know what exactly is going on here, and why the date formatter and calendar date components don't agree?
Please note: There are valid reasons this value needs to be 1 unit of least precision lower than the next day. I am aware that I could just subtract 1 second, however that is not what is being questioned. What is in question is why the date formatter believes the day of the date below is 18 when it should be 17.