【问题标题】:Time difference between two times in iPhoneiPhone中两次之间的时差
【发布时间】:2012-05-04 11:44:58
【问题描述】:

我有两次:

10:23:51
10:31:54

这两个值都作为字符串存储在 SQLite 数据库中。

我想以 hh:mm 格式找出这两次之间的差异。
我该怎么做?

我搜索了很多。但找不到合适的解决方案。 帮帮我。 谢谢。

编辑: 基本上我有两个数组:
InTimeArrayOuttimeArray。 现在在 viewDidload 方法中,我正在获取 IntimeArrayOuttime 数组中的所有 intime 条目。

现在我像第一行一样在 tableview 中一个一个地传递值

 IntimeArray[0]
 OuyTimeArray[0]

第二行:

 IntimeArray[1]
 OuyTimeArray[1]

现在我想以 HH:MM 格式计算第一行的 intimeouttime 之间的差异。
我真的很困惑。

【问题讨论】:

    标签: iphone ipad sqlite date


    【解决方案1】:

    你可以看看:

    -(NSDate *)dateFromString:(NSString *)string
    {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dateFormat setLocale:locale];
    [dateFormat setDateFormat:@"HH:mm:ss"];
    
    NSDate *date1 = [dateFormat dateFromString:string];  
    if(!date1) date1= [NSDate date];
    [dateFormat release];
    [locale release];
    
    return date1;
    }
    

    这会将 NSDate 转换为您,当您将它们都更改为 NSDate 时,您可以通过查看 this 了解差异。

    我希望这会对你有所帮助..

    【讨论】:

      【解决方案2】:

      您必须首先使用此方法将两个字符串都更改为日期格式:-

      - (NSDate *)dateFromString:(NSString *)string;
      

      之后你只需要计算两个日期之间的秒数。就是这样。

      还有另一种简单的方法可以做到这一点。即

      首先从两个数组中获取日期,如下所示:-

      NSDate *eventStartDate = [IntimeArray objectAtIndex:indexpath.row];
      
      NSDate *eventEndDate = [OuyTimeArray objectAtIndex:indexpath.row];
      

      然后像这样计算两个日期之间的差异:-

      NSTimeInterval startTimeInterval = [eventStartDate timeIntervalSinceDate:currentDate];
      

      希望对你有帮助谢谢:)

      【讨论】:

      • 我有 NSDate *eventStartDate = [IntimeArray objectAtIndex:indexpath.row]; NSDate *eventEndDate = [OuyTimeArray objectAtIndex:indexpath.row];
      • 我已经按照你说的那样使用了这段代码。但是它给了我关于不兼容类型“NSInterval”的错误
      • 我想比较 eventStartDate 和 eventEndDate 之间的差异
      【解决方案3】:

      试试这个:

      NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
      [formatter setDateFormat:@"HH:mm:ss"];
      
      NSDate *d1 = [formatter dateFromString:IntimeArray[0]];
      NSDate *d2 = [formatter dateFromString:OuyTimeArray[0]];
      
      NSTimeInterval ti = [d2 timeIntervalSinceDate:d1];
      float hours = floor(ti / 3600);
      float minutes = floor((ti - hours*3600) / 60);
      
      NSString *s = [NSString stringWithFormat:@"%02.0f:%02.0f",hours,minutes];
      

      对于您给定的示例,NSLog(@"Time passed: %@",s); 将打印 00:08

      【讨论】:

      • 嘿,我正在把我编辑的代码放在你引用的地方..它给了我错误。
      • 如果您收到错误,那么您的NSString(来自IntimeArray[0])的格式不正确(即“HH:mm:ss”)。在创建日期之前,通过NSLog() 将字符串打印出来,确保字符串具有这种格式。
      • 在我的应用程序中必须有 H:mm:ss 格式先生...如果我要更改此格式会导致如此多的更改..有什么办法吗?
      • 请发布您在运行此代码时遇到的错误。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 2018-04-03
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      相关资源
      最近更新 更多