2015-04-27 79 views

回答

-2

試試這個

- (NSString *)timeFormatted:(int)totalSeconds 
{ 

    int seconds = totalSeconds % 60; 
    int minutes = (totalSeconds/60) % 60; 
    int hours = totalSeconds/3600; 

    return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds]; 
} 
+0

你想怎麼做你的答案。這不屬於問題。 –

+0

我知道,但它也是很好的方式HH:MM:SS可能是爲什麼我給ans如此sory –

7

請嘗試以下的檢索int值碼。

@try { 
    NSString *myString = @"5 hours 10 min"; 
    NSArray *myWords = [myString componentsSeparatedByCharactersInSet: 
         [NSCharacterSet characterSetWithCharactersInString:@" "] 
         ]; 
    int hoursValue = 0, minuteValue = 0; 
    hoursValue = [[myWords objectAtIndex:0] intValue]; 
    if([myWords count] > 2) { 
     minuteValue = [[myWords objectAtIndex:2] intValue]; 
    } 

    NSLog(@"hours %d and Minute %d",hoursValue,minuteValue); 
} 
@catch (NSException * e) { 
    NSLog(@"Exception: %@", e); 
} 
+0

請將此代碼嘗試捕獲其他明智如果您的合作伙伴更改它可能會導致您的應用程序崩潰 –

0

試試這個

@try 
    { 
      NSString *myString = @"5 hours 10 min"; 
      NSArray *myWords = [myString componentsSeparatedByString:@" "]; 
      int hoursValue = 0, minuteValue = 0; 
      if ([myWords count] == 4) 
      { 
       hoursValue = [[myWords objectAtIndex:0] intValue]; 
       minuteValue = [[myWords objectAtIndex:2] intValue]; 

      } 
      else if([myWords count] == 2) 
      { 
       if([[myWords objectAtIndex:1] isEqualToString:@"hours"] == yes) 
       { 
        hoursValue = [[myWords objectAtIndex:0] intValue]; 
       } 
       else 
       { 
        minuteValue = [[myWords objectAtIndex:0] intValue]; 
       } 
      } 
      NSLog(@"hours %d and Minute %d",hoursValue,minuteValue); 
    } 
    @catch(Exception *exception 
    { 
    } 
0

使用一個NSDateFormatter到字符串1轉換成一個NSDate,然後得到所需的NSDateComponents:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"<Date format>"]; 
    NSDate *date = [dateFormatter dateFromString:string1]; 
    NSCalendar *calendar = [NSCalendar currentCalendar]; 
    NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date]; 
    NSInteger hour = [components hour]; 
    NSInteger minute = [components minute]; 

瞭解更多here

0

試試這個:

int hr,mins; 
NSString *[email protected]"5 hours 10 min"; 
NSArray *firstWords = [str componentsSeparatedByString:@" "]; 
if (([[firstWords objectAtIndex:1] isEqualToString:@"hours"]||[[firstWords objectAtIndex:1] isEqualToString:@"hr"]) &&([[firstWords objectAtIndex:3] isEqualToString:@"minutes"]||[[firstWords objectAtIndex:3] isEqualToString:@"min"])) { 
    hr=(int)[[firstWords objectAtIndex:0]integerValue]; 
    mins=(int)[[firstWords objectAtIndex:2]integerValue]; 
    if (mins > 60) { 
     hr+=mins/60; 
     mins =mins%60; 

    } 
} 
相關問題