【问题标题】:Performance issue finding weekdays over a given period在给定时间段内查找工作日的性能问题
【发布时间】:2011-02-19 07:55:10
【问题描述】:

我有一些方法可以返回两个给定日期之间的工作日数。由于当两个日期相隔数年时调用这些方法变得非常昂贵,我想知道如何以更有效的方式重构这些方法。 返回的结果是正确的,但我觉得 iphone 处理器正在努力跟上,因此当我在 10 年内调用这些方法时冻结了应用程序。 有什么建议吗?

    //daysList contains all weekdays that need to be found between the two dates
    -(NSInteger) numberOfWeekdaysFromDaysList:(NSMutableArray*) daysList 
                                              startingFromDate:(NSDate*)startDate 
                                              toDate:(NSDate*)endDate
    {
     NSInteger retNumdays = 0;

     for (Day *dayObject in [daysList objectEnumerator])
     {
      if ([dayObject isChecked])
      {
       retNumdays += [self numberOfWeekday:[dayObject weekdayNr] startingFromDate:startDate toDate:endDate];
      }
     }

     return retNumdays;
    }


    -(NSInteger) numberOfWeekday:(NSInteger)day 
                                 startingFromDate:(NSDate*)startDate 
                                 toDate:(NSDate*)endDate
    {
     NSInteger numWeekdays = 0;
     NSDate *nextDate = startDate;

     NSComparisonResult result = [endDate compare:nextDate];

     //Do while nextDate is in the past
     while (result == NSOrderedDescending || result == NSOrderedSame) 
     {
      if ([NSDate weekdayFromDate:nextDate] == day)
      {
       numWeekdays++; 
      }

      nextDate = [nextDate dateByAddingDays:1];
      result = [endDate compare:nextDate];
     }

     return numWeekdays;
    }

【问题讨论】:

    标签: iphone objective-c cocoa cocoa-touch


    【解决方案1】:

    为什么不看看处理日期的核心基础类?

    CFAbsoluteTimeGetDayOfWeek 返回一个整数,表示指定绝对时间所指示的星期几。

    SInt32 CFAbsoluteTimeGetDayOfWeek ( CFAbsoluteTime 在, CFTimeZoneRef tz );

    参数 at :转换的绝对时间。 tz :用于时间校正的时区。为 GMT 传递 NULL。

    返回值: 表示 at 指定的星期几的整数 (1-7)。根据 ISO-8601,星期一用 1 表示,星期二用 2 表示,依此类推。

    可用性 在 iOS 2.0 及更高版本中可用。 宣布于 CFDate.h

    更多信息请访问:http://developer.apple.com/library/ios/#documentation/CoreFoundation/Conceptual/CFDatesAndTimes/

    【讨论】:

      【解决方案2】:

      您需要创建一个公式来计算工作日的数量,而不是每天循环并计算它们。

      类似这样的东西(这是一个粗略的近似),其中 startJD 和 endJD 是Julian Dates

      nWeekdays = (endJD - startJD) * 5 / 7;  
      

      当然,这很接近,但并不准确,因为它没有考虑一周中的哪一天开始和结束。但这是一般的想法,你需要一个公式,而不是一个循环。

      您也可以在 this topic by searching 上找到很多内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-05
        • 1970-01-01
        • 2012-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多