从NSDate减去分钟

我想减去一些分钟15分钟10分钟等等,而我现在有时间对象现在我想减去分钟。     
已邀请:
看看我对这个问题的回答:NSDate减去一个月 以下是针对您的问题修改的示例:
NSDate *today = [[NSDate alloc] init];
NSLog(@"%@", today);
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setMinute:-10]; // note that I'm setting it to -1
NSDate *endOfWorldWar3 = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
NSLog(@"%@", endOfWorldWar3);
希望这可以帮助!     
使用以下:
// gives new date object with time 15 minutes earlier
NSDate *newDate = [oldDate dateByAddingTimeInterval:-60*15]; 
    
从iOS 8开始,有更方便的
dateByAddingUnit
//subtract 15 minutes
let calendar = NSCalendar.autoupdatingCurrentCalendar()
newDate = calendar.dateByAddingUnit(.CalendarUnitMinute, value: -15, toDate: originalDate, options: nil)
    
从Swift 2.x开始,当前的Swift答案已经过时了。这是一个更新版本:
let originalDate = NSDate() // "Jun 8, 2016, 12:05 AM"
let calendar = NSCalendar.currentCalendar()
let newDate = calendar.dateByAddingUnit(.Minute, value: -15, toDate: originalDate, options: []) // "Jun 7, 2016, 11:50 PM"
NSCalendarUnit
OptionSetType
的值已改为
.Minute
,你不能再为
options
传入
nil
。相反,使用一个空数组。 使用新的
Date
Calendar
类更新Swift 3:
let originalDate = Date() // "Jun 13, 2016, 1:23 PM"
let calendar = Calendar.current
let newDate = calendar.date(byAdding: .minute, value: -5, to: originalDate, options: []) // "Jun 13, 2016, 1:18 PM"
更新上面的Swift 4代码:
let newDate = calendar.date(byAdding: .minute, value: -5, to: originalDate) // "Jun 13, 2016, 1:18 PM"
    

要回复问题请先登录注册