51

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)
Abdurrahman Mubeen Ali
  • 1,331
  • 1
  • 13
  • 19
Rahul Vyas
  • 28,260
  • 49
  • 182
  • 256

6 Answers6

149

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];
Rui Lopes
  • 2,562
  • 6
  • 34
  • 49
Tom Jefferys
  • 13,090
  • 2
  • 35
  • 36
19

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)
Ben Packard
  • 26,102
  • 25
  • 102
  • 183
2

You can simply use:

NSDate *incrementedDate = [NSDate dateWithTimeInterval:numberOfSeconds sinceDate:[NSDate date]];
TechSeeko
  • 1,521
  • 10
  • 19
0

You can simply add 8 * 3600 to your database value (assuming that your converted double value represents seconds).

Pascal
  • 16,846
  • 4
  • 60
  • 69
0

NSDate *startdate = datePicker.date;

    NSTimeInterval secondsInOneHours = 1 * 60 * 60;

    NSDate *dateOneHoursAhead = [startdate dateByAddingTimeInterval:secondsInOneHours];

    [dateformate setDateFormat:@"d-MMM-yy HH:mm:ss"];

    strDate = [dateformate stringFromDate:dateOneHoursAhead];
Venu Gopal Tewari
  • 5,672
  • 42
  • 41
0

Swift 3.X Simple usage

let calendar = NSCalendar.autoupdatingCurrent
let newDate = calendar.date(byAdding: .hour, value: 8, to: Date())
SwiftDeveloper
  • 7,244
  • 14
  • 56
  • 85