Подтвердить что ты не робот

Формат строки iOS в минутах и ​​секундах

Я получаю строку из JSONC api YouTube, но продолжительность идет как полный номер i.e 2321 вместо 23:21 или 2 вместо 0:02. Как я могу это исправить?

JSON C

EDIT:

int duration = [videos valueForKey:@"duration"];
int minutes = duration / 60;
int seconds = duration % 60;

NSString *time = [NSString stringWithFormat:@"%d:%02d", minutes, seconds];
4b9b3361

Ответ 1

Предполагая, что значение длительности действительно является длительностью в секундах, вы можете рассчитать количество минут и секунд, а затем отформатировать их в строку.

int duration = ... // some duration from the JSON
int minutes = duration / 60;
int seconds = duration % 60;

NSString *time = [NSString stringWithFormat:@"%d:%02d", minutes, seconds];

Ответ 2

Вы должны использовать DateComponentsFormatter, если продолжительность предназначена для пользователя:

let formatter = DateComponentsFormatter()
formatter.allowedUnits = [ .minute, .second ]
formatter.zeroFormattingBehavior = [ .pad ]
let formattedDuration = formatter.string(from: duration)!

Ответ 3

Попробуйте этот оптимизированный

+ (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];
}

Ответ 4

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);

Ответ 5

Здесь - отличный код, который я нашел для этого

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

Ответ 6

Вы можете subString 2321 и получить первую строку как 23, а вторую - как 21 и преобразовать их в int. Также проверьте длину текста:

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

Ответ 7

Цель C:

NSDateComponentsFormatter * formatter = [[NSDateComponentsFormatter alloc]init];
[formatter setUnitsStyle:NSDateComponentsFormatterUnitsStyleShort];
[formatter setAllowedUnits:NSCalendarUnitSecond | NSCalendarUnitMinute];
[formatter setZeroFormattingBehavior:NSDateComponentsFormatterZeroFormattingBehaviorPad];
return [formatter stringFromTimeInterval:duration];