【问题标题】:Convert NSTimeInterval to NSString in iPhone?在 iPhone 中将 NSTimeInterval 转换为 NSString?
【发布时间】:2010-11-25 14:31:35
【问题描述】:

如何将 NSTimeInterval 转换为 NSString?我有

NSTimeInterval  today = [[NSDate date] timeIntervalSince1970];

我必须将“今天”作为 NSString 的输入。

【问题讨论】:

    标签: iphone nsstring nstimeinterval


    【解决方案1】:

    NSTimeInterval 只是一个 double 类型,所以你可以使用 +stringWithFormat: 方法将其转换为字符串

    NSTimeInterval  today = [[NSDate date] timeIntervalSince1970];
    NSString *intervalString = [NSString stringWithFormat:@"%f", today];
    

    【讨论】:

    • 谢谢,我尝试使用 %@ 而不是 %f。
    • %@ 仅适用于对象。此外,响应-description 消息的对象。
    • @jer,或者似乎是localizedDescription...无论如何描述方法是在NSObject中定义的,所以它的所有后代都会响应它
    • NSObject 的所有后代都可以,但 NSProxy 的后代不会。抱歉,我没有说清楚。
    • 实际上你说得很好——因为大多数类都继承自 NSObject 并响应 -description: 方法,因此很容易忽略并意外调用那些不响应的对象
    【解决方案2】:
    -(NSString*)formattedDuration:(NSTimeInterval)interval{
        NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
        formatter.allowedUnits = NSCalendarUnitHour | NSCalendarUnitMinute;
        formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
        NSString *string = [formatter stringFromTimeInterval:interval];
        NSLog(@"%@", string);
        // output: 0:20:34
        return string;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-29
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多