Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios NSDateFormatter和NSDateComponents为周数返回不同的值_Ios_Objective C_Nsdateformatter_Nsdatecomponents - Fatal编程技术网

Ios NSDateFormatter和NSDateComponents为周数返回不同的值

Ios NSDateFormatter和NSDateComponents为周数返回不同的值,ios,objective-c,nsdateformatter,nsdatecomponents,Ios,Objective C,Nsdateformatter,Nsdatecomponents,我正在制作一个创建时间表的应用程序。您可以每周创建一个新的。当应用程序完成加载后,需要加载当前周(例如:如果是1月1日,则需要显示第1周)。我使用NSDateFormatter确定当前星期是什么 NSDateFormatter (我在2016年8月9日对此进行了测试) 我想检查它是否工作,所以我使用了NSLog NSLog(@"%i", currentWeek); NSLog(@"%@", theFireDate); 它返回了32 NSDateComponents 所以NSDateForma

我正在制作一个创建时间表的应用程序。您可以每周创建一个新的。当应用程序完成加载后,需要加载当前周(例如:如果是1月1日,则需要显示第1周)。我使用NSDateFormatter确定当前星期是什么

NSDateFormatter

(我在2016年8月9日对此进行了测试)

我想检查它是否工作,所以我使用了NSLog

NSLog(@"%i", currentWeek);
NSLog(@"%@", theFireDate);
它返回了
32

NSDateComponents

所以NSDateFormatter认为当前一周是
32
。到目前为止,一切顺利。应用程序需要发送推送通知,告知用户某个时段即将开始。因此,应用程序使用NSDateComponents安排通知

// Setting the notification's fire date.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setWeekday:3];  // Because it's on a Tuesday
[dateComps setWeekOfYear:currentWeek];  // 32
[dateComps setYear:2016];
[dateComps setHour:12];
[dateComps setMinute:20];
NSDate *theFireDate = [calendar dateFromComponents:dateComps];

// Creates the notification.
UILocalNotification *Alert = [[UILocalNotification alloc] init];
Alert.timeZone = [NSTimeZone defaultTimeZone];
Alert.alertBody = @"This is a message!";
Alert.fireDate = theFireDate;
[[UIApplication sharedApplication] scheduleLocalNotification:Alert];
我还使用了NSLog

NSLog(@"%i", currentWeek);
NSLog(@"%@", theFireDate);

但它返回的
2016-08-02 12:20:00+0000
不是当前日期。它实际上是当前日期减去7天,或提前一周。那么这是否意味着当前一周实际上是
33
而不是
32
,这意味着NSDateFormatter是错误的?或者它实际上是
32
,这意味着NSDateComponents是错误的。是什么导致这两者之间的差异呢?

不要使用
NSDateFormatter
,使用更准确的
NSCalendar

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSInteger weekOfYear = [calendar component:NSCalendarUnitWeekOfYear fromDate:[NSDate date]];

尝试将区域设置和时区设置为日期格式化程序,然后再次调试。不要问我为什么,但是使用
NSCalendar*calendar=[NSCalendar currentCalendar]
,它可以工作(我有一个格里高利日历),但是使用它的alloc/init,我遇到了相同的问题。似乎在某个地方错过了一个场景。如果我设置
[calendar setLocale:[NSLocale currentLocale]],它可以工作。我同意,看起来您的时区、区域设置和日历不匹配。