我想從字符串中獲得小時和分鐘的整數變量「5小時10分鐘」。任何人都可以爲我提供解決方案。ios將字符串「5小時10分鐘」轉換爲整數小時和分鐘
NSString *duration [email protected]"5 hours 10 min";
int hours = 5
int min = 10
我想從字符串中獲得小時和分鐘的整數變量「5小時10分鐘」。任何人都可以爲我提供解決方案。ios將字符串「5小時10分鐘」轉換爲整數小時和分鐘
NSString *duration [email protected]"5 hours 10 min";
int hours = 5
int min = 10
試試這個
- (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];
}
你想怎麼做你的答案。這不屬於問題。 –
我知道,但它也是很好的方式HH:MM:SS可能是爲什麼我給ans如此sory –
請嘗試以下的檢索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);
}
請將此代碼嘗試捕獲其他明智如果您的合作伙伴更改它可能會導致您的應用程序崩潰 –
試試這個
@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
{
}
使用一個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
試試這個:
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;
}
}
你想在兩個不同的變量? –
你嘗試了什麼?你嘗試過'NSDateFormatter'嗎? –
@ Er.Shreyansh Shah是 –