How does one subtract hours from an NSDate?

蹲街弑〆低调 提交于 2019-11-27 03:03:22

问题


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 = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate * mydate = [dateFormatter dateFromString:[dict objectForKey:@"published"]];

What do I do next?


回答1:


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

Link to documentation.


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

Link to documentation.




回答2:


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.




回答3:


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: [])



回答4:


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



回答5:


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.




回答6:


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

NSDate * theDate = [dateFormatter dateFromString:datetemp];




回答7:


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
}


来源:https://stackoverflow.com/questions/1160977/how-does-one-subtract-hours-from-an-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!