how do I set an existing NSDate's time?

Greg picture Greg · Mar 19, 2011 · Viewed 26.3k times · Source

how do I set an existing NSDate's time?

That is I have a date (say current date/time), but then want to set this to a specific time (e.g. 11.23am) say. What is the quickest way to do this in objective C?

I'm looking at NSCalendar and see methods such as dateByAddingComponents:toDate:options:, and dateFromComponents:, but these don't seem to quite hit the mark for what I need here. For example:

  1. dateFromComponents: - I would have to work out all components for this to work which seems like overkill
  2. dateByAddingComponents:toDate:options: - I don't want to ADD in my case but rather "set" the time.

Answer

Alexsander Akers picture Alexsander Akers · Mar 19, 2011
NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setHour: 7];
[components setMinute: 59];
[components setSecond: 17];

NSDate *newDate = [gregorian dateFromComponents: components];

I use NSUIntegerMax instead of specific OR-combined bit masks because it's easier, but if you want to specify which data components to receive, be my guest.