开发者

Subtract minutes from NSDate

I want to subtract some minutes 15 min 10 min etc., And i am having date object with time now i want to subtract minute开发者_JAVA百科s.


Use following:

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


Check out my answer to this question: NSDate substract one month

Here's a sample, modified for your question:

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

Hope this helps!


Since iOS 8 there is the more convenient dateByAddingUnit:

//subtract 15 minutes
let calendar = NSCalendar.autoupdatingCurrentCalendar()
newDate = calendar.dateByAddingUnit(.CalendarUnitMinute, value: -15, toDate: originalDate, options: nil)


The current Swift answer is outdated as of Swift 2.x. Here's an updated version:

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"

The NSCalendarUnit OptionSetType value has changed to .Minute and you can no longer pass in nil for options. Instead, use an empty array.

Update for Swift 3 using the new Date and Calendar classes:

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"

Update the code above for Swift 4:

let newDate = calendar.date(byAdding: .minute, value: -5, to: originalDate) // "Jun 13, 2016, 1:18 PM"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜