【问题标题】:Working with NSDate and Comparing with Dates in Objective C在 Objective C 中使用 NSDate 和比较日期
【发布时间】:2011-01-05 23:48:35
【问题描述】:

“2010 年 12 月 31 日上午 9:00 至下午 1:00”

以上面的 NSString 为例,我需要将它转换为 2 个 NSDates,例如 2010 年 12 月 31 日上午 9:00 和 2010 年 12 月 31 日下午 1:00

然后将其与当前日期进行比较,以查看当前日期是否在给定日期内。

所以 2010 年 12 月 31 日上午 10:00 将在范围内。

我想知道 Objective C 的最佳实践/技巧是什么?

【问题讨论】:

  • 为了比较,我喜欢转换为 unixtime(这是内置在 obj-c 中的),但这只是我的偏好!
  • 在阅读使用 NSDate 的 compare: 方法的代码时,我总是不得不考虑比我想要的更长的时间,所以我在 NSDate 上编写了一个实现 lessThan:、lessThanOrEqual: 等的类别,它使用了 compare:下。我发现编码时更容易阅读。

标签: iphone objective-c nsstring nsdate nstimeinterval


【解决方案1】:

【讨论】:

    【解决方案2】:

    我最终这样做了:

        NSString *temp = [[dateString allValues] objectAtIndex:0];
    
        NSLog(@"temp: %@", temp);
    
    
        NSArray *tokens = [temp componentsSeparatedByString: @" "];
    
    
        NSArray *tokenOneDelimited =  [[tokens objectAtIndex:0] componentsSeparatedByString: @"-"];
    
    
        NSString *dateStr1 = [NSString stringWithFormat: @"%@-%@-%@ %@",    [tokenOneDelimited  objectAtIndex:2],
                                                                            [tokenOneDelimited  objectAtIndex:1],
                                                                            [tokenOneDelimited  objectAtIndex:0],
                                                                            [tokens             objectAtIndex:1]];
    
        NSString *dateStr2 = [NSString stringWithFormat: @"%@-%@-%@ %@",    [tokenOneDelimited  objectAtIndex:2],
                              [tokenOneDelimited    objectAtIndex:1],
                              [tokenOneDelimited    objectAtIndex:0],
                              [tokens               objectAtIndex:3]];
    
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    
        [dateFormatter setDateFormat:@"yyyy-MMM-dd hh:mma"];
    
        NSDate *myDate1 = [dateFormatter dateFromString: dateStr1];
    
        NSDate *myDate2 = [dateFormatter dateFromString: dateStr2];
    
        NSDate *currentDate = [NSDate date];
    
        NSComparisonResult comparison = [currentDate compare: myDate1];
    
        NSComparisonResult comparison2 = [currentDate compare: myDate2];
    
    
        if ( 
            comparison      == NSOrderedDescending &&
            comparison2     == NSOrderedAscending
            )
        {
            NSLog(@"is On now");
    

    【讨论】:

      猜你喜欢
      • 2010-12-14
      • 2011-01-16
      • 2010-11-02
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      相关资源
      最近更新 更多