从NSDate减去分钟数

时间:2011-02-14 04:32:50

标签: ios nsdate nstimeinterval

我想减去一些分钟15分钟10分钟等等,而且我现在有时间对象,我想减去分钟。

3 个答案:

答案 0 :(得分:67)

使用以下内容:

// gives new date object with time 15 minutes earlier
NSDate *newDate = [oldDate dateByAddingTimeInterval:-60*15]; 

答案 1 :(得分:25)

查看我对此问题的回答:NSDate substract one month

以下是针对您的问题进行修改的示例:

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);

希望这有帮助!

答案 2 :(得分:6)

从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,您无法再为nil传递options。相反,请使用空数组。

使用新的DateCalendar类更新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"