kiran kumar kiran kumar - 7 months ago 59
Objective-C Question

How to get time interval for every 30:00(30 minutes) from current time to 10:30 pm

need help to show the time intervals for every 30 mins suppose the

current time is 11:45 am

Time intervals:12:00 pm,12:30 pm,01:00 pm,01:30 pm,02:00 pm,02:30 pm......10:30 pm.

NSString *time = @"10.30 pm";

NSDate *date1;
NSDate *date2;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@" a"];
date1 = [formatter dateFromString:time];
date2 = [formatter dateFromString:[formatter stringFromDate:[NSDate date]]];

NSTimeInterval interval = [date1 timeIntervalSinceDate: date2];//[date1 timeIntervalSince1970] - [date2 timeIntervalSince1970];
int hour = interval / 3600;
int minute = (int)interval % 3600 / 60;

NSLog(@"%@ %dh %dm", interval<0?@"-":@"+", ABS(hour), ABS(minute));

This code returns me difference of current time and the given time how can i proceed further.


You can do something like,

NSString *startTime = @"02:00 AM";
NSString *endTime = @"11:00 AM";

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"hh:mm a"];
NSDate* fromTime = [timeFormat dateFromString:startTime];
NSDate* toTime = [timeFormat dateFromString:endTime];
NSDate *dateByAddingThirtyMinute ;
NSTimeInterval timeinterval = [toTime timeIntervalSinceDate:fromTime];
NSLog(@"time Int %f",timeinterval/3600);
float numberOfIntervals = timeinterval/3600;
NSLog(@"Start time %f",numberOfIntervals);

for(int iCount = 0;iCount<numberOfIntervals*2 ;iCount ++)
    dateByAddingThirtyMinute = [fromTime dateByAddingTimeInterval:1800];
    fromTime = dateByAddingThirtyMinute;
    NSString *formattedDateString;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm a"];
    formattedDateString = [dateFormatter stringFromDate:dateByAddingThirtyMinute];
    NSLog(@"Time after 30 min %@",formattedDateString);

In for loop i have taken numberOfIntervals*2 because time interval is 30 min so 60/30 = 2. If you want time after avery 10 minutes then it should 60/10 = 6, so it should numberOfIntervals*6. And your datebyAddingThirtyMinute should be [fromTime dateByAddingTimeInterval:600];

Hope this will help :)