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.

4 Answers 4

75

Use following:

// gives new date object with time 15 minutes earlier
NSDate *newDate = [oldDate dateByAddingTimeInterval:-60*15]; 
2
  • 1
    @Ishu Make sure you are not passing an unsigned integer.I did that mistake.
    – akc
    Sep 20, 2014 at 9: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. Jun 24, 2015 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!

1
  • NSGregorianCalendar is deprecated from iOS 8 onwards. Maybe we can update this answer.
    – TheJeff
    Feb 16, 2017 at 22:34
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)
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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.