22

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

4

4 回答 4

74

使用以下:

// gives new date object with time 15 minutes earlier
NSDate *newDate = [oldDate dateByAddingTimeInterval:-60*15]; 
于 2011-02-14T04:38:42.877 回答
25

查看我对这个问题的回答: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);

希望这可以帮助!

于 2011-02-14T04:53:49.857 回答
11

由于 iOS 8 有更方便dateByAddingUnit

//subtract 15 minutes
let calendar = NSCalendar.autoupdatingCurrentCalendar()
newDate = calendar.dateByAddingUnit(.CalendarUnitMinute, value: -15, toDate: originalDate, options: nil)
于 2015-05-10T13:35:50.380 回答
8

当前的 Swift 答案在 Swift 2.x 中已经过时了。这是一个更新的版本:

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,您不能再传入nilfor options。相反,请使用空数组。

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"
于 2016-06-08T04:07:01.607 回答