Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 minutes.

like image 223
Ishu Avatar asked Feb 14 '11 04:02

Ishu


4 Answers

Use following:

// gives new date object with time 15 minutes earlier
NSDate *newDate = [oldDate dateByAddingTimeInterval:-60*15]; 
like image 63
jamihash Avatar answered Nov 16 '22 15:11

jamihash


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!

like image 27
donkim Avatar answered Nov 16 '22 16:11

donkim


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)
like image 30
Ben Packard Avatar answered Nov 16 '22 15:11

Ben Packard


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"
like image 9
JAL Avatar answered Nov 16 '22 17:11

JAL