0

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

 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 语句。

4

1 回答 1

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);
于 2012-09-03T04:41:18.303 回答