【问题标题】:Comparing NSDate + Period比较 NSDate + 期间
【发布时间】:2014-02-15 07:05:12
【问题描述】:

我有开始日期和持续时间(期间)。例如startDate = '2014-02-12'period = 2。我想要日期2014-02-12、2014-02-14、2014-02-16、...。我需要确定当前日期是否在其中标记。

【问题讨论】:

  • 你能添加一些示例代码吗?
  • 开始日期是 NSDate 还是 NSString?你试过什么? “标记当前日期”是什么意思?
  • 以 NSDate 形式给出的开始日期。如果当前日期等于 2014-02-12, 2014-02-14, 2014-02-16, ....

标签: iphone objective-c nsdate


【解决方案1】:

检查开始日期和当前日期之间的差值是否为偶数 天数,使用NSDateComponents:

NSDate *startDate = ...;
NSDate *currentDate = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *diff = [cal components:NSDayCalendarUnit fromDate:startDate
                                  toDate:currentDate options:0];
NSInteger days = diff.day;
if (days % 2 == 0) {
    // even number of days between start date and current date
}

【讨论】:

  • 请注意,components:fromDate:toDate:options: 方法会将计算结果截断为提供的最小单位。例如,如果 fromDate: 参数对应于 2010 年 1 月 14 日晚上 11:30,而 toDate: 参数对应于 2010 年 1 月 15 日上午 8:00,则两个日期之间只有 8.5 小时。如果你问天数,你得到 0,因为 8.5 小时小于 1 天。在某些情况下,这应该是 1 天。您必须确定用户在特定情况下期望的行为。
  • 查看我的回答,如果您需要两个日期之间的天数,作为中间的午夜数。
  • @lancy:你说得对,我认为startDate 是第一天的开始(00:00)。如果不是这种情况,则可以使用 [cal rangeOfUnit:NSDayCalendarUnit startDate:&beginningOfStartDate interval:NULL forDate:startDate]; 轻松实现。
【解决方案2】:

您可以使用

获取所需的日期

- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds

seconds = period*3600*24

【讨论】:

  • 没有。不是每一天都有24小时。想想夏令时转换。
【解决方案3】:

计算从startDate到givenData的天数,检查结果是否能被周期整除。

+ (NSInteger)daysWithinEraFromDate:(NSDate *)startDate toDate:(NSDate *)endDate {
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    [gregorian setTimeZone:[NSTimeZone localTimeZone]];
    // for timezone issue
    NSDate *newDate1 = [startDate dateByAddingTimeInterval:[[NSTimeZone localTimeZone] secondsFromGMT]];
    NSDate *newDate2 = [endDate dateByAddingTimeInterval:[[NSTimeZone localTimeZone] secondsFromGMT]];
    NSInteger startDay = [gregorian ordinalityOfUnit:NSDayCalendarUnit
                                            inUnit: NSEraCalendarUnit forDate:newDate1];
    NSInteger endDay = [gregorian ordinalityOfUnit:NSDayCalendarUnit
                                          inUnit: NSEraCalendarUnit forDate:newDate2];
    return endDay - startDay;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-30
    • 2011-01-16
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    • 2011-08-03
    • 2012-02-18
    • 1970-01-01
    相关资源
    最近更新 更多