Imran Imran - 4 months ago 12
Objective-C Question

Converting String to Time Format returns nil Data

My Json is

{
"MinPerAppointment": "30",
"OpeningTime": "12:05"
}


Now, I want to Add 30 to 12:05, which Should be 12:35, I could not get How to format it, SO, I tried it with NSdate

NSString *str_MinPerAppointment = timeDetailData.minPerAppointment;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"];
NSDate *myDate = [dateFormatter dateFromString:str_MinPerAppointment];

NSString *dateInString = [dateFormatter stringFromDate:myDate];
NSLog(@"New AppointMentValue :%@",dateInString);


I am getting New AppointMentValue as nil

Answer

I don't think you need to use NSDate formatting. Simply convert HH:MM to minutes (or seconds, if you deal with them), do your math and then convert back.

Something like:

NSString *time = @"12:30";
int addMinutes = 30;
int hh, mm;
if (sscanf([time UTF8String], "%d:%d", &hh, &mm) == 2) {
    int minutes = (hh * 60) + mm;
    minutes += addMinutes;
    hh = minutes / 60;
    mm = minutes - (hh * 60);
    hh %= 24;    // day roll-over
    NSString *newTime = [NSString stringWithFormat:@"%02:%02d", hh, mm];
} else {
    NSLog(@"Invalid time value: %@", time);
}