Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add hours to an NSDate?

I have a date converted to double value and saved in database. Now, I want to compare if currentDate > myDataBaseDate + 8 hours i.e., I want to get 8 hours added to myDataBaseDate. I'm converting date into double values. So how do I get 8 hours later time from my database saved date. How do I compare

if (currentDateTime > DateFromdatabaseValue + DateByAdding8HoursInDataBase)
like image 799
Rahul Vyas Avatar asked Oct 31 '09 13:10

Rahul Vyas


3 Answers

I'm not entirely sure what you are trying to do, but you can create an NSDate object by adding time in seconds on to another NSDate using:

- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds

// eg. to add 8 hours to current time:

NSDate *mydate = [NSDate date];
NSTimeInterval secondsInEightHours = 8 * 60 * 60;
NSDate *dateEightHoursAhead = [mydate dateByAddingTimeInterval:secondsInEightHours];
like image 155
Tom Jefferys Avatar answered Nov 05 '22 02:11

Tom Jefferys


Since iOS 8 there is the more convenient dateByAddingUnit:

//add 8 hours
let calendar = NSCalendar.autoupdatingCurrentCalendar()
newDate = calendar.dateByAddingUnit(.CalendarUnitHour, value: 8, toDate: originalDate, options: nil)
like image 38
Ben Packard Avatar answered Nov 05 '22 00:11

Ben Packard


You can simply use:

NSDate *incrementedDate = [NSDate dateWithTimeInterval:numberOfSeconds sinceDate:[NSDate date]];
like image 2
TechSeeko Avatar answered Nov 05 '22 00:11

TechSeeko