【发布时间】:2011-02-14 04:32:49
【问题描述】:
我想减去一些分钟 15 分钟 10 分钟等,我现在有带时间的日期对象,现在我想减去分钟。
【问题讨论】:
标签: ios nsdate nstimeinterval
我想减去一些分钟 15 分钟 10 分钟等,我现在有带时间的日期对象,现在我想减去分钟。
【问题讨论】:
标签: ios nsdate nstimeinterval
使用以下:
// gives new date object with time 15 minutes earlier
NSDate *newDate = [oldDate dateByAddingTimeInterval:-60*15];
【讨论】:
NSCalendar 答案会利用已经为您处理所有边缘情况的现有功能集。
查看我对这个问题的回答: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);
希望这会有所帮助!
【讨论】:
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"
NSCalendarUnitOptionSetType 的值已更改为 .Minute,您不能再将 nil 传递给 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"
【讨论】: