从几周/几周的几天计算某些NSDates

时间:2015-07-09 11:44:01

标签: ios objective-c time nsdate nscalendar

是否有一种简单的方法可以根据NSCalendar和/或NSCalendarComponents的条件计算日期?我已经看了一段时间的文档,但似乎有点复杂。例如,我需要 "周三下午6:00"以及接下来的15个偶数周(如果它的编号均为偶数且未超过该日期/时间,则包括此项。)

2 个答案:

答案 0 :(得分:0)

这是一种方法,用于确定哪个星期三开始,然后获得接下来的14周甚至星期三。这不会考虑您问题的时间部分,但您可以使用类似的方法来处理时间。

+ (NSArray *)nextFifteenEvenNumberedWeekWednesdays:(NSDate *)startingDate
{
    static const NSInteger Wednesday = 4;
    static const NSInteger OneDay = 60 * 60 * 24;
    NSCalendar *calender = [NSCalendar currentCalendar];
    NSDateComponents *startingDateComponents = [calender components:(NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitWeekday | NSCalendarUnitWeekOfYear)
                                                           fromDate:startingDate];

    // Go to the closest Wednesday
    NSInteger daysToWednesday = Wednesday - startingDateComponents.weekday;
    if (startingDateComponents.weekday > Wednesday) {
        // We already passed wednesday, so go to the next wednesday
        if (startingDateComponents.weekOfYear % 2 == 0) {
            // If this date is past Wednesday but is on an even week, then moving to the next wednesday
            // will be an odd week. So skip forward one week.
            startingDate = [startingDate dateByAddingTimeInterval:7 * OneDay];
        }
        daysToWednesday = 7 + daysToWednesday; // get the next Wednesday
    }
    startingDate = [startingDate dateByAddingTimeInterval:daysToWednesday * OneDay]; // Move to wednesday

    NSMutableArray *wednesdays = [NSMutableArray array];
    for (NSInteger i = 0; i < 15; i++) {
        // Add every other wednesday
        [wednesdays addObject:[startingDate dateByAddingTimeInterval:14 * i * OneDay]];
    }

    return [wednesdays copy];
}

答案 1 :(得分:0)

我最后回答了自己的问题。当您知道function<-function(vector){ n<-length(vector) d<-data.frame(a=1:n, b=1:n, c=1:n) for (i in 1:n) { tryCatch({ #create an m for every i in vector m<-foo(i) for (j in 1:length(m[,1])) { #for every element in m, transform with a function m[j]<-foo2(j) } #now, with m transformed, fill every element of d (so that it matches elements of vector) d[i,]$a = sum(m) d[i,]$b = sd(m) d[i,]$c = mean(m) #end try }, error = function(e){ #if there is an erorr in m<-foo(i), I want it to place NULL or NA values in each column of d d[i,]$a = NULL d[i,]$b = NULL d[i,]$c = NULL } #end trycatch ) #end loop } #end function } 自动递增到下一个匹配日期时,这真的很容易。

-[NSCalendar dateBySettingUnit:value:ofDate:options:]