How does one subtract hours from an NSDate?

Miriam Roberts picture Miriam Roberts · Jul 21, 2009 · Viewed 27.7k times · Source

I would like to subtract 4 hours from a date. I read the date string into an NSDate object use the following code:

NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate * mydate = [dateFormatter dateFromString:[dict objectForKey:@"published"]];

What do I do next?

Answer

Georg Schölly picture Georg Schölly · Jul 21, 2009
NSDate *newDate = [theDate dateByAddingTimeInterval:-3600*4];

Link to documentation.


NSDate *newDate = [[[NSDate alloc] initWithTimeInterval:-3600*4
                                              sinceDate:theDate]] autorelease];

Link to documentation.