【问题标题】:How to format time with NSDateFormatter like this HH:mm:ss [duplicate]如何像这样使用 NSDateFormatter 格式化时间 HH:mm:ss [重复]
【发布时间】:2013-09-06 07:07:13
【问题描述】:

我有以秒为单位的歌曲的持续时间。

经过以下计算,我得到了小时、分钟和秒的时间。

int hour = time / 3600;
int minute = (time / 60) % 60;
int second = time % 60;

我需要用这种格式 HH:mm:ss 显示它们

我该怎么做?

【问题讨论】:

  • 您只是想在标签/ UIView 上将其显示为文本吗?
  • 就像大多数答案指出的那样,您所要求的不需要 NSDateFormatter
  • 你不能这样显示吗:NSLog(@"Final OutPut>> %02d:%02d:%02d", hour, minute, second);

标签: iphone ios objective-c nsdateformatter nsdatecomponents


【解决方案1】:

试试看

int hour = time / 3600;
int minute = (time / 60) % 60;
int second = time % 60;

 NSString *dateStr = [NSString stringWithFormat:@"%d %d %d",hour,minute,second];

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"HH:mm:ss"];
    NSDate *date1 = [dateFormat dateFromString:dateStr];

希望对你有所帮助。

【讨论】:

  • 为什么要从字符串中创建日期?更何况你给的日期格式和字符串不匹配。
【解决方案2】:

根据您的描述,您不需要使用 NSDateFormatter

int hour = time / 3600;
int minute = (time / 60) % 60;
int second = time % 60;

NSString *yourDate = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, minute, second, null];

【讨论】:

  • 它的格式是否适用于所有案例?
  • yes : '%02d' 显示一个至少有两位数的 int,如有必要,在前面添加 '0' :0 变为 '00',1 变为 '01',...当数字为大于 9 保持不变
【解决方案3】:

这将追加 0 并使其正好是 2 个字符..

NSString *str = [NSString stringWithFormat:@"%02d:%02d:%02d",hour,minute,second ];

【讨论】:

    【解决方案4】:

    可能会有帮助

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

    【讨论】:

      【解决方案5】:
      NSString *time = [NSString stringWithFormat:@"%d:%d:%d", hour, minute, second];
      

      【讨论】:

      • 应使用%02d 而不是%d
      【解决方案6】:

      试试这个代码

         float seconds = totalSeconds % 60; 
         float minutes = (totalSeconds / 60) % 60; 
         float hours = totalSeconds / 3600; 
         return [NSString stringWithFormat:@"%02f:%02f:%02f",hours, minutes, seconds];
      

      【讨论】:

      • 秒、分和小时应该是整数而不是浮点数
      猜你喜欢
      • 1970-01-01
      • 2011-10-28
      • 2019-07-13
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      • 1970-01-01
      相关资源
      最近更新 更多