如何创建每周范围(超过5年)的NSDate查找表

时间:2012-09-03 03:45:57

标签: objective-c ios nsdate nsdictionary nsdateformatter

不确定如何最好地实现这一点。

 NSDate *date = [NSDate date]; 

我需要对日期进行查找并返回字符串值。

12/17/2011 < date < 12/23/2011  return "20120101"

12/24/2011 < date < 12/30/2012   return "20120102"

12/31/2011 < date < 01/06/2012   return "20120201"

...

10/20/2012 < date < 10/26/2012  return "20122301"

...

11/02/2013 < date < 11/08/2013   return "20132301"

...

5年......每周

日期可以是2017年12月之前的任何日期。

我不知道返回字符串背后的逻辑,所以我不能简单地根据日期计算字符串。返回字符串(在模型中转换为NSDate)成功用作我的fetchedresultscontroller的部分。

我不确定如何基于NSDate创建查找表,或者我是否需要一些怪物if / case语句。

1 个答案:

答案 0 :(得分:1)

我会计算相关日期的“周数”,然后从字符串数组中获取值。这应该适合你:

// Create an array of your strings.
// This would probably be best to read from a file since you have so many
NSArray *strings                = [NSArray arrayWithObjects:
                                   @"20120101",
                                   @"20120102",
                                   @"20120201",
                                   @"20122301",
                                   @"20132301", nil];

// Create a new date formatter so that we can create our dates.
NSDateFormatter *formatter      = [NSDateFormatter new];
formatter.dateFormat            = @"MM/dd/yyyy";

// Create the date of the first entry in strings.
// We will be using this as our starting date and will calculate the
// number of weeks that has elapsed since then.
NSDate *earliestDate            = [formatter dateFromString:@"12/17/2011"];

// The date to check
NSDate *dateToCheck             = [formatter dateFromString:@"01/12/2012"];

// Create a calendar to do our calculations for us.
NSCalendar *cal                 = [NSCalendar currentCalendar];

// Calculate the number of weeks between the earliestDate and dateToCheck
NSDateComponents *components    = [cal components:NSWeekCalendarUnit
                                         fromDate:earliestDate
                                           toDate:dateToCheck
                                          options:0];
NSUInteger weekNumber           = components.week;

// Lookup the entry in the strings array.
NSString *string;
if (weekNumber < [strings count])
{
    string = [strings objectAtIndex:weekNumber];
}

// Output is:  "String is: 20122301"
NSLog(@"String is: %@", string);