本文介绍了NSCalendar NSDateComponents YearofYear返回1,日期为2014-12-31的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取日期为'2014-12-31'的WeekofYear,但是它总是返回1而不是52这是我的代码:

I want to get weekofYear with date '2014-12-31' ,but it always return 1 not 52 here is my code:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit;
NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:[NSDate date]];

NSlog(@"%i",dateComponent.weekOfYear);


output  "1";

我知道结果正确,但是我想得到"52"而不是"1",如何解决?

I know result is right, but I want get "52" not '1',how to fix it?

推荐答案

另一种方法是使用NSDateComponents实例的yearForWeekOfYear属性.如果yearForWeekOfYear在传递给components:fromDate:的日期的年份之后,则为52周.

An alternative approach is to use the yearForWeekOfYear property of the NSDateComponents instance. If the yearForWeekOfYear is after the year of the date passed to components:fromDate:, then it is week 52.

例如

NSCalendar *calendar = [NSCalendar currentCalendar];

NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit | NSYearForWeekOfYearCalendarUnit;
NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:[NSDate date]];

NSInteger weekOfYear = dateComponent.weekOfYear;
if (dateComponent.yearForWeekOfYear > dateComponent.year)
    weekOfYear = 52;
NSLog(@"%i",weekOfYear); // 52

这篇关于NSCalendar NSDateComponents YearofYear返回1,日期为2014-12-31的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 03:34