-1

How can I calculate the time difference (in seconds) from now to a specific day and hour (e.g. 6 PM on the 20th day of next month)?

I tried a lot, but didn't succeed in finding an easy solution without calculating a lot and checking lots of different cases.

NSDate *now = [NSDate date];
NSDateComponents *dc = [[NSDateComponents alloc] init];
[dc setMonth:1];
MyTargetDateObject = [[NSCalendar currentCalendar] dateByAddingComponents:dc  toDate:now options:0];
    [dc release];

..just adds 1 month from now. The other examples e.g. here don't seem to apply somehow.

jscs
  • 63,694
  • 13
  • 151
  • 195
robeppef
  • 11
  • 3

1 Answers1

1

Something like this (you'll have to translate from Swift, but I'm sure you get the idea):

let now = NSDate()
let greg = NSCalendar(calendarIdentifier: NSGregorianCalendar)
let u : NSCalendarUnit = .CalendarUnitYear | .CalendarUnitMonth
var dc = greg!.components(u, fromDate: now)
dc.month += 1 // next month
dc.hour = 18 // at 6 PM
dc.day = 20 // on the 20th
let then = greg!.dateFromComponents(dc)!
let diff = then.timeIntervalSinceNow // time interval = seconds

Note that we can do date arithmetic by adding to the desired unit of an NSDateComponents. Also note that all Date <-> Date Components conversions require passing thru a calendar.

matt
  • 515,959
  • 87
  • 875
  • 1,141