-3

I am trying to create an NSDate object with a certain number of hours and minutes before a reference date.

For example:

Reference date = oct 21 2013 12:30 PM

date with 2 hours before and 40 minute before: oct 21 2013 9:50 AM

Is it possible to do this?

flux
  • 395
  • 1
  • 2
  • 13

2 Answers2

1

You can use NSDate method dateByAddingTimeInterval. It takes a NSTimeInterval double to add the number of seconds to the desired time. Check NSDate class, there are other method of interest for you. NSDate

J2theC
  • 4,412
  • 1
  • 12
  • 14
1

Use NSDateComponents.

NSDateComponents *dateComps = [[NSCalender currentCalender] components:(NSDayCalenderUnit | NSMonthCalenderUnit | NSYearCalenderUnit | NSHourCalenderUnit | NSMinuteCalenderUnit | NSSecondCalenderUnit) fromDate:now];
[dateComps setHour:[dateComps hour]-2]; // Subtract here
[dateComps setMinute:[dateComps minute]-40]; // Subtract here

// You can change all components here as above methods.

NSDate *dateResult=[[NSCalender currentCalender] dateFromComponents:dateComps];

NSLog("%@",dateResult);
Akshit Zaveri
  • 4,166
  • 6
  • 30
  • 59
  • This is in fact the better way to do date arithmetic, because it takes into account the vagaries of calendars and time zones. – jscs Oct 26 '13 at 23:16