How to add 1 min timeslot to NSDate object in iPhone

I can get any local local time. My requirement is that when I get the local time, I need to add 1 minute after each min to NSDate.for ex: I get the time like this: 11:22 and im capable of displaying the next min should be 11:23.

Please help me.

+3


source to share


3 answers


NSDate *currentDate = [NSDate date];
NSDate *datePlusOneMinute = [currentDate dateByAddingTimeInterval:60];

      



+10


source


Omarj's answer looks good for simple testing purposes, but I like to use this code:

NSDateComponents *changeComponent = [[NSDateComponents alloc] init];
changeComponent.second = 20;

NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDate *newDate = [theCalendar dateByAddingComponents:changeComponent toDate:[NSDate date] options:0];

      



As you can see, you can change the changeComponent to minutes, hours, days, or in my case, seconds! This is very useful for testing local notifications that I am currently working on.

The best advantage of this solution is that it respects the calendar, so there should be no problem adding hours when daylight saving time changes.

+2


source


Please check this code.

    NSString* dateString = @"9:33AM";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mma"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"Before Adding time %@",date);
NSDate *newDate = [date dateByAddingTimeInterval:14*60];
NSLog(@"After adding time %@",[formatter stringFromDate:newDate]);

      

+1


source







All Articles