How to add hours to an NSDate?

让人想犯罪 __ 提交于 2019-11-29 20:14:48
Tom Jefferys

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];

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)

You can simply use:

NSDate *incrementedDate = [NSDate dateWithTimeInterval:numberOfSeconds sinceDate:[NSDate date]];

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

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];

Swift 3.X Simple usage

let calendar = NSCalendar.autoupdatingCurrent
let newDate = calendar.date(byAdding: .hour, value: 8, to: Date())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!