【问题标题】:how to add the time in iphone?如何在iphone中添加时间?
【发布时间】:2011-01-19 23:03:56
【问题描述】:

我有三个字符串

str1 = @"00:14"; str2 = @"00:55"; str3 = @"00:10";

我需要将三个字符串添加为整数并以相同的时间格式显示

我该怎么办,请帮帮我

提前致谢

【问题讨论】:

    标签: iphone nsstring add


    【解决方案1】:

    在 Cocoa 中处理日期很有趣!您可以创建这样的方法:

    - (NSDate *)dateByAddingDates:(NSArray *)dates {
      NSCalendar *calendar = [NSCalendar currentCalendar];
      unsigned unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
      NSDate *date = [dates objectAtIndex:0];
      for (int i = 1; i < [dates count]; i++) {
        NSDate *newDate = [dates objectAtIndex:i];
        NSDateComponents *comps = [calendar components:unitFlags fromDate:newDate];
        date = [calendar dateByAddingComponents:comps toDate:date options:0];
      }
      return date;
    }
    

    并像这样使用它:

      NSString *str1 = @"00:14";
      NSString *str2 = @"00:55";
      NSString *str3 = @"00:10";
    
      NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
      [dateFormatter setDateFormat:@"mm:ss"];
    
      NSArray *dates = [NSArray arrayWithObjects:[dateFormatter dateFromString:str1],
                        [dateFormatter dateFromString:str2],
                        [dateFormatter dateFromString:str3], nil];
      NSDate *date = [self dateByAddingDates:dates];
    
      NSLog(@"%@", [dateFormatter stringFromDate:date]);
    

    【讨论】:

      【解决方案2】:

      要正确地做事,应该是这样的:

      • 使用NSDateFormatter 将字符串转换为NSDate 对象。
      • 使用[NSCalendar currentCalendar] 提取每个日期的NSDateComponents,尤其是NSMinuteCalendarUnit
      • 将日期组件的所有分钟相加,并将其设置为NSDateComponent 对象
      • (可选)使用您的日历将NSDateComponent 转换回NSDate

      愚蠢地做事,你会在:之后得到一个字符子串,在它上面调用intValue将字符串变成int,然后把它加起来。我不建议这样做,因为它可能会导致微妙和狡猾的错误。另外,已经有代码可以为您完成。 :)

      【讨论】:

        【解决方案3】:

        查看此相关主题:Comparing dates

        总之,首先使用 initWithString: 方法调用将字符串解析为 NSDates。此后,您可以根据需要添加和操作日期,最后只需将其格式化为正确的输出。

        希望这希望能澄清您的疑问。

        顺便说一句,Mac 开发者 SDK 参考可以在这里找到供您参考:- http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/cl/NSDate

        【讨论】:

          猜你喜欢
          • 2017-08-31
          • 1970-01-01
          • 1970-01-01
          • 2019-07-01
          • 2013-01-20
          • 1970-01-01
          • 2019-11-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多