23

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.

JAL
  • 41,701
  • 23
  • 172
  • 300
Ishu
  • 12,797
  • 5
  • 35
  • 51

4 Answers4

75

Use following:

// gives new date object with time 15 minutes earlier
NSDate *newDate = [oldDate dateByAddingTimeInterval:-60*15]; 
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
jamihash
  • 1,900
  • 1
  • 12
  • 15
  • 1
    @Ishu Make sure you are not passing an unsigned integer.I did that mistake. – akc Sep 20 '14 at 09:35
  • 2
    This is simpler but there are some edge cases it misses (leap seconds, for example). This applies any time you see something assuming there are 60 seconds in a minute, 60 minutes in an hour, or any other shortcut. Using the other `NSCalendar` answers to this question leverages an existing set of functionality that has already handled all of the edge cases for you. – Ben Packard Jun 24 '15 at 15:36
25

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!

Community
  • 1
  • 1
donkim
  • 13,119
  • 3
  • 42
  • 47
11

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)
Ben Packard
  • 26,102
  • 25
  • 102
  • 183
9

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"
Zeb
  • 1,715
  • 22
  • 34
JAL
  • 41,701
  • 23
  • 172
  • 300