【问题标题】:Storing Time Values and Comparing Them存储时间值并进行比较
【发布时间】:2011-11-28 16:33:42
【问题描述】:

我正在尝试获取时间点,然后进行比较。我已经想出了如何比较它们,但我正在尝试创建 NSDate 对象来代表一天中的时间,这会造成一些麻烦。我使用了NSDateFromComponents 并使用了setHour:setMinute: 函数,但它没有成功修改对象。它还需要自动将日期的其他组成部分设置为当前时间和日期。

比较对象:

static bool DateIsBetween(NSDate *beginDate, NSDate *date, NSDate *endDate) {
    return [date timeIntervalSince1970] > [beginDate timeIntervalSince1970] && [date    timeIntervalSince1970] < [endDate timeIntervalSince1970];
}

创建日期对象:

NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];

[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:todayDate];

NSDateComponents *genericTimeComponents = [[NSDateComponents alloc]init];

[genericTimeComponents setHour:5];
[genericTimeComponents setMinute:0];
[genericTimeComponents setDay:weekdayComponents.day];
[genericTimeComponents setYear:weekdayComponents.year];
[genericTimeComponents setMonth:weekdayComponents.month];


NSDateComponents *secondComps = [[NSDateComponents alloc]init];
[secondComps setHour:7];
[secondComps setMinute:0];
[secondComps setDay:weekdayComponents.day];
[secondComps setYear:weekdayComponents.year];
[secondComps setEra:weekdayComponents.era];
[secondComps setMonth:weekdayComponents.month];

【问题讨论】:

  • 在此处粘贴您的代码。这将有助于我们查明问题的根源。

标签: objective-c cocoa date time nsdate


【解决方案1】:

确保在您的日期比较函数中使用括号(只是为了清楚起见;从逻辑上讲,它应该可以正常工作):

 static bool DateIsBetween(NSDate *beginDate, NSDate *date, NSDate *endDate) {
    return (([date timeIntervalSince1970] > [beginDate timeIntervalSince1970]) && ([date    timeIntervalSince1970] < [endDate timeIntervalSince1970]));
}

对于这种情况,最好为 NSDate 类创建一个类别并编写一个 Objective-c 方法。

对于其余部分,我尝试了以下代码,它对我有用:

NSDate * now = [NSDate date];

NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];

[gregorian setTimeZone:[NSTimeZone localTimeZone]];

NSDateComponents *genericTimeComponents = [gregorian components:(NSWeekdayCalendarUnit |NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit |NSYearCalendarUnit|NSMonthCalendarUnit|NSEraCalendarUnit)
                                                      fromDate:now];

[genericTimeComponents setHour:5];
[genericTimeComponents setMinute:0];

//  Quick Check 
NSLog(@"GTC=%@", genericTimeComponents);

【讨论】:

  • 制作一个C函数没有错。事实上,将其作为类别中的方法存在 Apple 将创建(或已经私下拥有)同名方法的风险,在这种情况下,您的方法的行为方式与 Apple 的方法的行为方式之间的任何差异都会导致问题。跨度>
  • 这就是为什么在类别中创建方法时,始终在方法名称前加上您的 orgs 首字母。扩展一个类可以产生非常易读和易于使用的代码。从未暗示编写 C 函数有任何“错误”,这只是风格和一致性的问题。至少,我希望 OP 知道该选项。
猜你喜欢
  • 2015-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-29
  • 1970-01-01
  • 2011-09-16
  • 2021-12-26
相关资源
最近更新 更多