How does one subtract hours from an NSDate?

后端 未结 7 1437
长发绾君心
长发绾君心 2020-12-09 14:56

I would like to subtract 4 hours from a date. I read the date string into an NSDate object use the following code:

NSDateFormatter * dateFormatter = [[[NSDat         


        
7条回答
  •  有刺的猬
    2020-12-09 15:53

    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
    }
    

提交回复
热议问题