Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one subtract hours from an NSDate?

People also ask

How do you subtract timestamp from hours?

If you wanted to subtract 5 hours and 15 minutes from the date-timestamp you would subtract 5.25 / 24 = . 2187. If you needed to subtract 4 hours and 8 minutes, you would subtract 8 / 60 = . 133 and therefore 4.133 / 24 = .

How do you subtract time in Swift?

To subtract hours from a date in swift we need to create a date first. Once that date is created we have to subtract hours from that, though swift does not provide a way to subtract date or time, but it provides us a way to add date or date component in negative value.


NSDate *newDate = [theDate dateByAddingTimeInterval:-3600*4];

Link to documentation.


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

Link to documentation.


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


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 asking for trouble.


Since iOS 8 there is the more convenient dateByAddingUnit:

Swift 2.x

//subtract 3 hours
let calendar = NSCalendar.autoupdatingCurrentCalendar()
newDate = calendar.dateByAddingUnit(.Hour, value: -3, toDate: originalDate, options: [])

//in Swift 3
//subtract 3 hours
let calendar = NSCalendar.autoupdatingCurrent
newDate = calendar.date(byAdding:.hour, value: -3, to: originalDate)

Here a function which might be useful as it returns the date -4 h considering that this may also change the date and the month and eventually the year. the .searchBackward 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
}

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

NSDate * theDate = [dateFormatter dateFromString:datetemp];