objective-c - 如何创建具有每周范围(超过 5 年)的 NSDate 的查找表

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

最佳答案

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

// 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);

关于objective-c - 如何创建具有每周范围(超过 5 年)的 NSDate 的查找表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12241743/

相关文章:

Iphone屏幕视频捕捉

ios - 无法从 View 中删除 subview ?

ios - 使用 Objective C 在设备上播放声音

iphone - 将日期转换为 Unix 时间(自 1970 年以来的秒数)

swift - NSDate 忽略时区

ios - NSDate 到 TimeStamp 的转换和 NSDate 比较

ios - FBSession : an attempt was made reauthorize permissions on an unopened session

ios - 将 session 信息传输回 native 应用程序

iphone - 如何调用 Objective-C 对象中的变量

ios - initWithData 返回(空)