iOS格式的string分为几秒钟

我收到来自YouTube JSONC API的string,但是持续时间将以2321而不是23:21或2而不是0:02来表示。 我怎么去解决这个问题?

JSON C.

编辑:

int duration = [videos valueForKey:@"duration"]; int minutes = duration / 60; int seconds = duration % 60; NSString *time = [NSString stringWithFormat:@"%d:%02d", minutes, seconds]; 

假设持续时间值实际上是以秒为单位的持续时间,那么可以计算分钟数和秒数,然后将它们格式化为一个string。

 int duration = ... // some duration from the JSON int minutes = duration / 60; int seconds = duration % 60; NSString *time = [NSString stringWithFormat:@"%d:%02d", minutes, seconds]; 

试试这个非常优化

 + (NSString *)timeFormatConvertToSeconds:(NSString *)timeSecs { int totalSeconds=[timeSecs intValue]; int seconds = totalSeconds % 60; int minutes = (totalSeconds / 60) % 60; int hours = totalSeconds / 3600; return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds]; } 

如果持续时间旨在面向用户,则应该使用DateComponentsFormatter :

 let formatter = DateComponentsFormatter() formatter.allowedUnits = [ .minute, .second ] formatter.zeroFormattingBehavior = [ .pad ] let formattedDuration = formatter.string(from: duration)! 
 int sec = diff;//INFO: time in seconds int a_sec = 1; int a_min = a_sec * 60; int an_hour = a_min * 60; int a_day = an_hour * 24; int a_month = a_day * 30; int a_year = a_day * 365; NSString *text = @""; if (sec >= a_year) { int years = floor(sec / a_year); text = [NSString stringWithFormat:@"%d year%@ ", years, years > 0 ? @"s" : @""]; sec = sec - (years * a_year); } if (sec >= a_month) { int months = floor(sec / a_month); text = [NSString stringWithFormat:@"%@%d month%@ ", text, months, months > 0 ? @"s" : @""]; sec = sec - (months * a_month); } if (sec >= a_day) { int days = floor(sec / a_day); text = [NSString stringWithFormat:@"%@%d day%@ ", text, days, days > 0 ? @"s" : @""]; sec = sec - (days * a_day); } if (sec >= an_hour) { int hours = floor(sec / an_hour); text = [NSString stringWithFormat:@"%@%d hour%@ ", text, hours, hours > 0 ? @"s" : @""]; sec = sec - (hours * an_hour); } if (sec >= a_min) { int minutes = floor(sec / a_min); text = [NSString stringWithFormat:@"%@%d minute%@ ", text, minutes, minutes > 0 ? @"s" : @""]; sec = sec - (minutes * a_min); } if (sec >= a_sec) { int seconds = floor(sec / a_sec); text = [NSString stringWithFormat:@"%@%d second%@", text, seconds, seconds > 0 ? @"s" : @""]; } NSLog(@"<%@>", text); 

这是我发现这个伟大的代码

 int duration = 1221; int minutes = floor(duration/60) int seconds = round(duration - (minutes * 60)) NSString * timeStr = [NSString stringWithFormat:@"%i:%i",minutes,seconds]; NSLog(@"Dilip timeStr : %@",timeStr); 

而输出将是这样的

 Dilip timeStr : 20:21 

你可以subStringstring2321并获得第一个string为23,第二个为21,并将其转换为int 。 同时检查文本的长度:

 if (text.length < 4) //add zeros on the left of String until be of length 4