[ACCEPTED]-How does one subtract hours from an NSDate?-nsdate

Accepted answer
Score: 49
NSDate *newDate = [theDate dateByAddingTimeInterval:-3600*4];

Link to documentation.


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

Link to documentation.

0

Score: 23

NSCalendar is the general API for changing 3 dates based on human time units. For this, you 2 can use NSCalendar's -dateByAddingComponents:toDate:options: with a negative number 1 of hours.

Score: 9

In Swift 4 :

var baseDate = ... // something
let dateMinus4Hours = Calendar.current.date(byAdding: .hour, value: -4, to: baseDate)

don't go with 24*3600 and stuff, that's 1 asking for trouble.

Score: 6

Since iOS 8 there is the more convenient 1 dateByAddingUnit:

Swift 2.x

//subtract 3 hours
let calendar = NSCalendar.autoupdatingCurrentCalendar()
newDate = calendar.dateByAddingUnit(.Hour, value: -3, toDate: originalDate, options: [])
Score: 5
//in Swift 3
//subtract 3 hours
let calendar = NSCalendar.autoupdatingCurrent
newDate = calendar.date(byAdding:.hour, value: -3, to: originalDate)

0

Score: 2

Here a function which might be useful as 4 it returns the date -4 h considering that 3 this may also change the date and the month 2 and eventually the year. the .searchBackward 1 option is the important part :)

public static func correctSecondComponent(date: Date, calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian))->Date {

    let hour = calendar.component(.hour, from: date)

    let e = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.hour, value: -4, to: date, options:.searchBackwards)!

    return e
}
Score: 1

dateFromString function returns NSDate, not 2 NSString. you should change,

NSDate * theDate 1 = [dateFormatter dateFromString:datetemp];

More Related questions